Is there anyway for me to identify whether an object/record is dirty before saving and which fields are changed in Rails?
Example
Suppose I have a Person model and Person has a property called name and age. In the db, Person with id 1 is named “John” with age 20.
p = Person.find 1
p.name #John
p.age #20
now, when I change his name from John to Nathan, is there any way for me to identify
- the the object is changed (dirty)
- and which fields got changed
Now I know the answer for the first one. If I change his name to Nathna, I can do the following
p.name = "Nathan"
p.changed? #true
However, is there anyway for me to identify which field was changed? May be a method that returns an array of fields that got changed?
p.dirty_fields #[:name]
See http://api.rubyonrails.org/classes/ActiveModel/Dirty.html#method-i-changes, specifically
changed.