Rails, using the dirty or changed? flag with after_commit
I heard rails has a dirty/change flag. Is it possible to use that in the after_commit callback?
In my user model I have:
after_commit :push_changes
In def 开发者_运维百科push_changes
I would like a way to know if the name field changed. Is that possible?
You can use previous_changes in after_commit to access a model's attribute values from before it was saved.
see this post for more info: after_commit for an attribute
You can do a few things to check...
First and foremost, 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 in the entire model:
user = User.find(1)
user.changed # => []
user.name = "Bob"
user.age = 42
user.changed # => ['name', 'age']
There's a few more things you can do too - check out http://api.rubyonrails.org/classes/ActiveModel/Dirty.html for details.
Edit:
But, given that this is happening in an after_commit
callback, the model has already been saved, meaning knowledge of the changes that occurred before the save are lost. You could try using the before_save
callback to pick out the changes yourself, store them somewhere, then access them again when using after_commit
.
Since Rails 5.1, in after_commit
you should use saved_change_to_attribute?
Ref: Rails 5.1.1 deprecation warning changed_attributes
精彩评论