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
    • 798
    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.

    Example:

    user = User.first
    user.name # => John
    user.changed?       # => false
    
    
    
    user.name = '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.save
    user.changes       # => {}
    user.previous_change # => {"name"=>["John", "John Snow"]}
    

    We can reset the changes by reloading the model.

    user.reload
    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
        write_attribute(:password_edited_on, Time.now)
      end
    
    end
    
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
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: