Skip to content

Instantly share code, notes, and snippets.

@cheeyeo
Last active December 9, 2015 21:51
Show Gist options
  • Save cheeyeo/95d7e57f8de5541c068c to your computer and use it in GitHub Desktop.
Save cheeyeo/95d7e57f8de5541c068c to your computer and use it in GitHub Desktop.
Tracking ActiveRecord model changes

Introduction ActiveModel::Dirty is a library that is built into Ruby on Rails that allows you to quickly and easily determine what attributes on a model have changed. This short article will show you how to use it. Let's get started.

Checking Whether the Model Has Changed Checking whether the model has changed is accomplished using the changed? method:

product.changed? # => false If we change an attribute on the model, the changed? method returns true:

product.name = "Candy" product.changed? # => true Determining The Change We can determine what the change was using the attr_change method:

product.name_change # => ["Bubble Gum", "Candy"] We can also get a list of all of the changed attributes on the model like so:

product.changed # => ["name"] We can also get the original value using the attr_was method:

product.name_was #=> "Bubble Gum We can view a list of all of the original values using the changed_attributes method:

product.changed_attributes # => {"name" => "Bubble Gum"} We can also list all of the changes on the model using the changes method:

product.changes # => {"name" => ["Bubble Gum", "Candy"]} We can view changes that were made even after the model was saved using the previous_changes method:

product.save
product.changes       # => {}
product.previous_changes        # => {"name" => ["Bubble Gum", "Candy"]}

Finally we can reset the model using the reload! method:

product.reload! product.previous_changes # => {}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment