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?
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.
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.
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.
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.
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.
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