Rails using dirty or modified? flag with after_commit

I heard that the rails have a dirty / removable flag. Can this be used in the after_commit callback?

In my user model, I have:

after_commit :push_changes 

In def push_changes I need a way to find out if the name field has changed. Is it possible?

+8
ruby-on-rails ruby-on-rails-3 activemodel
source share
2 answers

You can do a few things to check ...

First of all, you can check an individual attribute as such:

 user = User.find(1) user.name_changed? # => false user.name = "Bob" user.name_changed? # => true 

But you can also check which attributes have changed throughout the model:

 user = User.find(1) user.changed # => [] user.name = "Bob" user.age = 42 user.changed # => ['name', 'age'] 

A few more things you can do are more detailed at http://api.rubyonrails.org/classes/ActiveModel/Dirty.html .

Edit:

But, given that this happens in the after_commit , the model is already saved, that is, knowledge of the changes that occurred before the save was lost. You can try using the before_save to select the changes yourself, store them somewhere, and then access them again when using after_commit .

+10
source share

You can use previous_changes in after_commit to access model attribute values ​​before saving it.

see this post for more info: after_commit for attribute

+19
source share

All Articles