Is there a Rails way to check which attributes were updated in the observer?

I have an ActivityObserver that observes tasks and has an after_update .

I want to check if a specific attribute has been changed in update .

Is there a way for Rails to compare the attributes of an object with what it was before the update, or to check if they were changed?

+7
ruby-on-rails observer-pattern attributes
source share
2 answers

When the after_update callback is executed, each ActiveModel object has a method called changed_attributes . You can verify this in your debugging environment. Each ActiveRecord object has this method. It has a hash of all values ​​that have been changed / changed. This is also called the Dirty object.

Check out some of these guides.

Railscasts

Dirty object

+9
source share

Your observer should have something like the following.

 class ActivityObserver < ActiveRecord::Observer def after_update(activity) if activity.attribute_name_changed? puts "The above condition will return true or false, and this time it has returned true..!!!" end end end 

The above method will work. I think you were looking for this.

+1
source share

All Articles