Activerecord callback, previous_changes vs. changes

十年热恋 提交于 2020-01-05 04:06:16

问题


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

https://apidock.com/rails/v4.2.7/ActiveModel/Dirty/changes

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.

Am I misunderstanding this?


回答1:


yes you understood it rightly

These are dirty object methods

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.

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

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 => {}

Note

You can also look at this answer for more help.



来源:https://stackoverflow.com/questions/45016584/activerecord-callback-previous-changes-vs-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!