Kush Kella
Kush Kella

Reputation: 1213

Tracking model changes in after_commit :on => :create callback

Is there a way to track changes to model on after_commit when a record is created? I have tried using dirty module and was able to track changes when the record was updated, but when record is created changes are not recorded.

Upvotes: 24

Views: 9278

Answers (1)

Santanu
Santanu

Reputation: 960

You can't use the rails changed? method, as it will always return false. To track changes after the transaction is committed, use the previous_changes method. It will return a hash with attribute name as key. You can can then check if your attribute_name is in the hash:

after_commit :foo

def foo
 if previous_changes[attribute_name]
   #do your task
 end
end

Upvotes: 54

Related Questions