Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Dirty methods in Rails model

    • 0
    • 1
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 763
    Comment on it

    Sometimes we face a situation where after changing the value of an attribute of an object we need the previous or the unchanged value for some purpose. We generally store the previous value in a variable to be used later. Instead of this approach we can use these methods that are provided by ActiveModel::Dirty class.


    user = User.first # => John
    user.changed?       # => false
     = 'John Snow'
    user.changed?       # => true
    user.name_changed?  # => true
    user.name_was       # => John
    user.name_change    # => ["John", "John Snow"]
    user.changes # => {"name"=>["John", "John Snow"]}

    We can see the changes even after saving the object.
    user.changes       # => {}
    user.previous_change # => {"name"=>["John", "John Snow"]}

    We can reset the changes by reloading the model.

    user.previous_changes # => {}

    Based on the above methods we can write callbacks in the model.

    class User < ActiveRecord::Base
      before_update :set_password_edited,  if: encrypted_password_changed?
        def set_password_edited

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: