nfm
nfm

Reputation: 20687

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?

Upvotes: 7

Views: 3196

Answers (2)

Rohit
Rohit

Reputation: 5721

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

Upvotes: 10

Nishutosh Sharma
Nishutosh Sharma

Reputation: 1936

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 ..

Upvotes: 1

Related Questions