Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there anyway to undo an activerecord delete in rails console?

Tags:

I have made an unbelievably horrible mistake in script/console:

user.delete 

Is there any way to undo that from within the same script/console session?

like image 495
Phil R Avatar asked Aug 14 '12 03:08

Phil R


People also ask

What is the difference between delete and destroy in rails?

Basically destroy runs any callbacks on the model while delete doesn't. Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted). Returns the frozen instance.

What is Activerecord in Ruby on rails?

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.

How do you delete a record in rails?

By using destroy, you can delete the record from rails as well as its other existing dependencies. So in the context of our rails application, if we delete a book record using the destroy function, the authors associated with the book will also be deleted.

How do you clear a table in rails?

Step 1: Generate a migration that drops the table. The following command creates an empty migration file. Step 2: Now, use the drop_table method, providing the table's name. This method tells rails to drop that table from the database when running the migration.


1 Answers

Well, if you remain to have access to the deleted record, you can just create a new replica like this

User.new(user.attributes_hash).save 

That will just create a user with the exaxt same attributes (yes, also the id) and save it to the DB. I use this to undo a destroy action using the flash.

Caveat. If you have used the User#destroy method and your model has relations with dependent: :destroy or dependent: :delete, then those dependent records – if present when executing the command – will be lost. Unless, of course, you have active references, i.e. variables, to the deleted/destroyed records.

like image 134
Arne L. Avatar answered Jan 03 '23 12:01

Arne L.