Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Delete all Records that Meet a Condition

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.

like image 587
Noam B. Avatar asked Oct 10 '12 18:10

Noam B.


People also ask

How delete all data from table in rails?

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.

How do you delete data in rails?

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.

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 does dependent destroy mean rails?

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.


1 Answers

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 
like image 178
MurifoX Avatar answered Sep 18 '22 14:09

MurifoX