Using ActiveModel::Dirty for tracking changes
ActiveRecord
comes with a mechanism to track changes to your model with ActiveModel::Dirty
. Lets put it to some use.
I had a requirement where I needed to track changes in certain places in my rails app.
When saving any record in Rails, if we look at the queries carefully, we can see that each query does not have all values but just the changed ones.
Above query is fired after changing email to tejas@asd.com
and saving the object.
Clearly ActiveRecord
keeps track of changes on its objects. This mechanism is provided by the ActiveModel::Dirty
module.
We can see the changes before the record is being saved.
Note that changes
method gives changes only before saving the record.
Once the record is saved, the changes are flushed out and ready to record new ones.
In order to track changes in existing codebase which has many occurrences like @model.update_attributes()
I needed some way to know changes after the record is saved.
ActiveModel
to the rescue! When the changes are flushed out after saving, they are not immediately thrown away but kept under another instance variable
and can be accessed via previous_changes
method.
References:
-
ActiveModel provides other methods which can be found in the docs.
-
Or dive into ActiveModel source code.