Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 277
nfm Avatar asked Oct 11 '10 05:10

nfm


2 Answers

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

like image 100
Rohit Avatar answered Nov 09 '22 15:11

Rohit


There must be something like following in your observer.

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 do. I think you were looking for this ..

like image 25
Nishutosh Sharma Avatar answered Nov 09 '22 16:11

Nishutosh Sharma