Some times we wanted to know what are the previous values for an object.
We can track the unsaved attribute changes in Rails.
These can be used before save only.
The below are the methods you can use.
* changed
* changed?
* changes
Eg:
Before Assigning:
user = User.find(1)
user.first_name # => "Naga"
user.last_name # => "Harish"
user.changed? # => false
user.changed # => []
After Assigning:
user.first_name = "Turvi"
user.last_name = "Sri"
user.changed? # => true
user.changes # => {"first_name"=>["Naga", "Turvi"], "last_name"=>["Harish", "Sri"]}
user.changed # => ["first_name", "last_name"]
You can also you the dirty suffixes.
DIRTY_SUFFIXES = ['_changed?', '_change', '_will_change!', '_was']
user.first_name_changed? # => true
user.first_name_change # => ["Naga", "Turvi"]
user.first_name_was # => "Naga"
user.first_name_will_change! # => "Turvi"
NOTE: Once you save this record
changed? will become false.
So you can have History as one more table or one more column called update_history as column to store all the
changes.