Determining if a record / object in Rails is dirty

In any case, I need to determine if the 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 time. In db, a person with id 1 is called "John" with an age of 20.

p = Person.find 1 p.name #John p.age #20 

now that i am changing my name from john to nathan is there any way to identify

  • object changed (dirty)
  • and which fields have been changed

Now I know the answer for the first. If I change my name to Natna, I can do the following

 p.name = "Nathan" p.changed? #true 

However, one way or another, can I determine which field has been changed? Maybe a method that returns an array of fields that have been changed?

 p.dirty_fields #[:name] 
+7
source share
1 answer
+8
source

All Articles