Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying whether record/object is dirty in Rails

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

  1. the the object is changed (dirty)
  2. 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]
like image 509
denniss Avatar asked Aug 27 '11 00:08

denniss


1 Answers

See http://api.rubyonrails.org/classes/ActiveModel/Dirty.html#method-i-changes, specifically changed.

like image 92
kylc Avatar answered Sep 24 '22 05:09

kylc