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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With