Search code examples
ruby-on-railsrubyactiverecord

How to revert/undo local changes to an Activerecord object?


Is there a way to undo/revert any local changes to an Activerecord object. For example:

user = User.first
user.name # "Fred"
user.name = "Sam"
user.name_was # "Fred"

user.revert
user.name # "Fred"

I know I could do user.reload but I shouldn't have to hit the database to do this since the old values are stored in the state of the object.

Preferably a Rails 3 solution.


Solution

  • You could just loop through the 'changes' and reset them. There might be a method that does this, but I didn't look.

    > c = Course.first
    > c.name
    => "Athabasca Country Club"
    > c.name = "Foo Bar"
    => "Foo Bar"
    > c.changes
    => {"name"=>["Athabasca Country Club", "Foo Bar"]}
    > c.changes.each {|k,vs| c[k] = vs.first}
    > c.name
    => "Athabasca Country Club"
    

    Actually looks like there is a "name_reset!" method you could call...

    > c.changes.each {|k,vs| c.send("#{k}_reset!")}