Today I Learned

A Hashrocket project

ActiveRecord Dirty module

Rails provides a way to check if your model’s attributes have changed since initially loading it from database. It also provides convenient methods for checking what the values were before the change using #{attribute_name}_was as in the example below.

# A newly instantiated object is unchanged:
person = Person.find_by_name('Uncle Bob')
person.changed?       # => false
  
# Change the name:
person.name = 'Bob'
person.changed?       # => true
person.name_changed?  # => true
person.name_was       # => 'Uncle Bob'
person.name_change    # => ['Uncle Bob', 'Bob']
person.name = 'Bill'
person.name_change    # => ['Uncle Bob', 'Bill']
  
# Save the changes:
person.save
person.changed?       # => false
person.name_changed?  # => false

# Assigning the same value leaves the attribute unchanged:
person.name = 'Bill'
person.name_changed?  # => false
person.name_change    # => nil
  
# Which attributes have changed?
person.name = 'Bob'
person.changed        # => ['name']
person.changes        # => { 'name' => ['Bill', 'Bob'] }
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.