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: = "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:

<pre class="prettyprint">
product.changes       # => {}
product.previous_changes        # => {"name" => ["Bubble Gum", "Candy"]}

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

product.previous_changes # => {}

Full documentation can be found at the Ruby on Rails API site. That's it! Thanks for reading!