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.
To undo a rails generate command, run a rails destroy command. You can then edit the file and run rake db:migrate again.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With