Search code examples
ruby-on-railsattributesobserver-pattern

Is there a Rails way to check which attributes have been updated in an observer?


I have an ActivityObserver, which is observing tasks, and has an after_update callback.

I want to test if a particular attribute has been modified in the update.

Is there a Rails way to compare the attributes of the subject with what they were before the update, or to check if they have changed?


Solution

  • When an after_update callback is being executed, every ActiveModel object has a method called changed_attributes. You can check it out in your debug environment. Every ActiveRecord object has this method. It has a hash of all the values that have been changed/modified. This is also known as Dirty object.

    Check out some of these tutorials

    Railscasts

    Dirty Object