Track changes in your active record object using Dirty Objects in Rails

If you want to track whether your active record objects have been modified or not. It becomes a lot easier with the dirty object functionality. It’s pretty straightforward and clean.

  article = Article.first
  article.changed?  #=> false

  # Track changes to individual attributes with# attr_name_changed? accessor
  article.title  #=> "Title"
  article.title = "New Title"
  article.title_changed? #=> true

  # Access previous value with attr_name_was accessor
  article.title_was  #=> "Title"

  # See both previous and current value with attr_name_change accessor
  article.title_change  #=> ["Title", "New Title"]

You can also query to object directly for its list of all changed attributes.

  # Get a list of changed attributes
  article.changed  #=> ['title']
  # Get the hash of changed attributes and their previous and current values
  article.changes  #=> { 'title' => ["Title", "New Title"] }

Once you save a dirty object it clears out its changed state tracking and is once again considered unchanged.

  article.changed?  #=> true  #=> truearticle.changed?  #=> false

If you’re going to be modifying an attribute outside of the attr= writer, you can use attr_name_will_change! to tell the object to be aware of the change:

  article = Article.first
  article.title_change  #=> ['Title', 'TITLE']