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)