Rails,用脏了还是改了?带有 after_commit 的标志
我听说 Rails 有一个脏/更改标志。是否可以在 after_commit 回调中使用它?
在我的用户模型中,我有:
after_commit :push_changes
在 def push_changes
中,我想要一种方法来知道名称字段是否更改。这可能吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在 after_commitprevious_changes strong> 访问保存模型之前的模型属性值。
请参阅这篇文章以获取更多信息:
属性的 after_commit
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
您可以做一些事情来检查...
首先,您可以检查单个属性:
但是,您也可以检查整个模型中哪些属性已更改:
您还可以做更多事情 - 检查请访问 http://api.rubyonrails.org/classes/ActiveModel/Dirty.html 了解详细信息。
编辑:
但是,考虑到这是在
after_commit
回调中发生的,模型已经被保存,这意味着保存之前发生的更改的知识会丢失。您可以尝试使用before_save
回调自行挑选更改,将它们存储在某处,然后在使用after_commit
时再次访问它们。You can do a few things to check...
First and foremost, you can check an individual attribute as such:
But, you can also check which attributes have changed in the entire model:
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 thebefore_save
callback to pick out the changes yourself, store them somewhere, then access them again when usingafter_commit
.从 Rails 5.1 开始,在
after_commit
中,您应该使用saved_change_to_attribute?
参考:Rails 5.1.1 弃用警告已更改_attributes
Since Rails 5.1, in
after_commit
you should usesaved_change_to_attribute?
Ref: Rails 5.1.1 deprecation warning changed_attributes