Ruby on Rails Model Change Tracking With ActiveModel::Dirty

Ruby on Rails Model Change Tracking with ActiveModel::Dirty

ActiveModel::Dirty is a library that is built into Ruby on Rails that allows you to quickly and easily track what attributes on a model have changed. This article will show you how to use it.

Checking Whenever the Model Has Changed
Checking whether the model has changed using the changed? method:

1
product.changed?  # => false

If you change an attribute on the model, the changed? method will returns true:

1
2
product.name = "Mac Pro"
product.changed? # => true

Tracking the Change
You can track what the change by using the attr_change method:

1
product.name_change # => ["Mac Pro", "IBM ThinkPad"]

You can get a list of all of the changed attributes on the model as well:

1
product.changed # => ["name"]

You can get the original value using the attr_was method as well:

1
product.name_was #=> "IBM ThinkPad"

You can view a list of all of the original values using the changed_attributes method as well:

1
product.changed_attributes # => {"name" => "IBM ThinkPad"}

You can list all of the changes on the model using the changes method as well:

1
product.changes # => {"name" => ["IBM ThinkPad", "Mac Pro"]}

You can view changes that were made even after the model was saved using the previous_changes method as well:

1
2
3
4
5
<pre class="prettyprint">
  product.save
  product.changes # => {}
  product.previous_changes # => {"name" => ["IBM ThinkPad", "Mac Pro"]}
</pre>

You can view changes that were made even after the model was saved using the previous_changes method as well:

1
2
3
4
5
<pre class="prettyprint">
  product.save
  product.changes # => {}
  product.previous_changes # => {"name" => ["IBM ThinkPad", "Mac Pro"]}
</pre>

You can reset the model using the reload! method as well:

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

So far so good, for more detail Ruby on Rails API. That’s it! See ya!