如何在保存时获取更改的值

Jac*_*han 0 ruby oop ruby-on-rails ruby-on-rails-3

尝试在保存时从对象获取先前的值.想想这种情况:

@object = {:name => 'Dan', :occupation => 'student'}
@object[:occupation] = 'Full time employee'
@object.value_was[:occupation] # => 'student'

我希望没有方法可以理解value_was.更多我想在模型对象上做同样的事情:

@student = Student.find(1)
@student.occupation = 'Full time employee'
@student.save
@student.value_was(:occupation) # => 'student'

任何帮助将不胜感激.

那会非常有帮助

Chr*_*ald 5

ActiveModel包括对" 脏字段标记 "的支持," 脏字段标记 "保留更改字段的状态之前和之后.

您可以使用@student.occupation_was获取之前的值occupation,并@student.occupation_changed?获取值是否已更改.

这仅在保存之前有效,因为保存会重置值的更改状态.但是,如果需要在保存记录后使用它,则可以在before_save回调中捕获此数据.您可以通过复制#changed_attributesa before_save,例如然后查询它们来保留所有更改.