Rails - Delete all Records that Meet a Condition

SqlRuby on-RailsActiverecord

Sql Problem Overview


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.

Sql Solutions


Solution 1 - Sql

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

Solution 2 - Sql

Try this:

Manager.delete_all(manager_level: 5)

Solution 3 - Sql

This should work:

Manager.where(:manager_level => 5).delete_all

Note: This will not remove dependent records.

Solution 4 - Sql

After Rails 5.1., We cannot pass conditions to delete_all/destroy_all method

Manager.where(:manager_level => 5).delete_all

> This will run multiple queries to delete each record

But in Rails 6, we can use delete_by to delete using condition,

Manager.delete_by(manager_level: 5)

> This will run single delete query > > delete from managers where manager_level = 5

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNoam B.View Question on Stackoverflow
Solution 1 - SqlMurifoXView Answer on Stackoverflow
Solution 2 - SqlAndrew HareView Answer on Stackoverflow
Solution 3 - SqliouriView Answer on Stackoverflow
Solution 4 - SqlNavarasuView Answer on Stackoverflow