Trying to get previous values from the object on save. Think of this scenario:
@object = {:name => 'Dan', :occupation => 'student'}
@object[:occupation] = 'Full time employee'
@object.value_was[:occupation] # => 'student'
I hope it is understandable enough that there is no method value_was. More over I would like to do the same on model objects:
@student = Student.find(1) @student.occupation = 'Full time employee' @student.save @student.value_was(:occupation) # => 'student'
Any help will be appreciated.
That would be really helpful
ActiveModel includes support for “dirty field marking“, which preserves before and after states for changed fields.
You can use
@student.occupation_wasto get the previous value ofoccupation, and@student.occupation_changed?to get whether the value has changed or not.This only works BEFORE the save, as saving resets the changed states of the values. However, you could capture this data in a before_save callback if you need to use it after a record has been saved. You can preserve all of the changes by duplicating
#changed_attributesin abefore_save, for example, then query on them.