Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 240
Tbabs Avatar asked Sep 06 '13 17:09

Tbabs


People also ask

How do you undo a destroy in rails?

To undo a rails generate command, run a rails destroy command. You can then edit the file and run rake db:migrate again.

What is Ruby Callbacks?

Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.

What is Active Record?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

As mentioned in this answer Rails 4.2 introduced the restore_attributes method in ActiveModel::Dirty:

user = User.first
user.name   # "Fred"
user.status # "Active"

user.name = "Sam"
user.status = "Inactive"
user.restore_attributes
user.name   # "Fred"
user.status # "Active"

If you want to restore a specific attribute, restore_attribute! can be used:

user.name = "Sam"
user.status = "Inactive"
user.restore_name!
user.name   # "Fred"
user.status # "Inactive"
like image 139
Peter Miller Avatar answered Oct 22 '22 00:10

Peter Miller