Activerecord callback, previous_changes vs. change

2019-08-24 14:04发布

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条回答
Melony?
2楼-- · 2019-08-24 14:48

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 => {}
查看更多
登录 后发表回答