Get Previously Saved Changes in Rails
31 Jul 2012Some times you need to see what fields changed in an object in Rails. I’ve known for awhile that you could do this before an object saved:
user = User.last
user.name = "schneems"
puts user.name_changed?
# => true
puts user.changes
# => {"name"=>["richard", "schneems"]}
but as soon as you save the object to the database you lose all that goodness.
user.save
puts user.name_changed?
# => false
puts user.changes
# => {}
What if we wanted to get the changes before those values were committed? We can use the previous_changes
method!
user.save
puts user.name_changed?
# => false
puts user.previous_changes
# => {"name"=>["richard", "schneems"], "updated_at"=>[Tue, 31 Jul 2012 18:53:12 UTC +00:00, Tue, 31 Jul 2012 18:56:49 UTC +00:00]}
It’s that simple. Go forth and make changes with impunity! Your previous results will be available when you need them.
(This only works when the object is still in memory, if you pull a user from the database changes
and previous_changes
will both be blank).