ActiveRecord回调,previous_changes与更改 [英] Activerecord callback, previous_changes vs. changes
问题描述
我试图了解这两种方法之间的区别。以下是每个文档:
I'm trying to understand what the difference between these two methods is. Here is the documentation for each:
https://apidock.com/rails/v4.2.7/ActiveModel/Dirty/previous_changes
>://apidock.com/rails/v4.2.7/ActiveModel/Dirty/changes
在阅读本文档后,我发现 previous_changes
是更改完成后的更改,即 after _ *
过滤器,而更改
是要更改的内容,这意味着它在 before _ *
过滤器。
It appears to me after reading this documentation that previous_changes
is what was changed after the changes are done, meaning in an after_*
filter, while changes
is what will be changed, meaning it's useful in a before_*
filter.
我误解了吗?
推荐答案
是的,您正确理解
这些是肮脏的对象方法
更改
是过去知道如果您尝试保存对象将发生的更改
previous_changes
曾经知道保存对象所反映的更改。
changes
is used to know the changes that would take place if you try to save an object
previous_changes
is used to know the changes that reflected by saving an object.
但是,如果您尝试重新加载对象,则更改
和 previous_changes
从数据库中获取记录的新副本时,将返回空的哈希{}。
But if you try to reload the object both changes
and previous_changes
would return empty hash {} as new copy of the record is being fetched from Database
例如,User(id:1,name:'Nimish',age:24,email :'test@example.com')
Eg User(id: 1, name: 'Nimish', age: 24, email: 'test@example.com')
user = User.find(1)
user.changes #Will output => {}
user.previous_changes #Will output => {}
user.name = 'Test User'
user.changes #Will output => {name: ['Nimish', 'Test User']}
user.previous_changes #Will output => {}
user.save
user.changes #Will output => {}
user.previous_changes #Will output => {name: ['Nimish', 'Test User']}
user.reload
user.changes #Will output => {}
user.previous_changes #Will output => {}
注意
您还可以查看此答案以获取更多帮助。
这篇关于ActiveRecord回调,previous_changes与更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!