By
on Rails, Ruby

Interesting Rails Feature - Active Model Dirty

This feature isn't used nearly as much as it deserves to be.

ActiveRecord objects keep a track of whether any of their attributes values have changed via the ActiveModel::Dirty module.

# Loading an object to memory
user = User.find 29  
# changed? lets us know whether any modifications were made to the object
u.changed? # => false  
# After Modifying the users name, we can see that changed? now returns a true
u.name = 'Frank'  
u.changed? # => true  
# changed can be used to let us know which attributes have been modified
u.changed  # ["name"]  
# #{attribute_name}_was can be used to obtain the former value
u.name_was # "Joliene"  
# #{attribute_name}_change returns an array consisting of the old and new values
u.name_change # ["Joliene", "Frank"]  

Next time, when temporarily assigning variables the values of object attributes before modifying them, remember that this functionality is already provided by Rails in an elegant way.

comments powered by Disqus