How do you write in the Rails way? I have a model - Managers. I want to delete all records from Managers that meet the condition that manager_level is 5.
Thank you.
During development, you might find yourself needing to delete everything from a specific database table to refresh your data. You could drop the whole database and bring it back up again with rake:db:drop, rake:db:setup , but that's slow and indiscriminate.
Rails delete operation using destroy method 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.
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.
If you set the :dependent option to: :destroy, when the object is destroyed, destroy will be called on its associated objects. :delete, when the object is destroyed, all its associated objects will be deleted directly from the database without calling their destroy method.
I think it is better to use destroy instead of delete
because destroy will delete current object record from db and also its associated children record from db (https://stackoverflow.com/a/22757656/5452072)
Also delete will skip callbacks, but destroy doesn't.
Manager.where(:manager_level => 5).destroy_all
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