How to Destroy multiple objects simultaneously in Rails 3

Ruby on-RailsRuby on-Rails-3

Ruby on-Rails Problem Overview


I have a Rails application that is trying to delete multiple objects at a time.

I have tried like sending set of id seperated by ',' to rails destroy method,but it destroy only single object. Is it possible to delete multiple objects in rails 3.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

destroy_all destroys the records matching conditions by calling destroy method for each instantiating record. So object’s callbacks are executed.

Model.destroy_all(:status => "inactive")
Model.where(:id => [1,2,3,4,5]).destroy_all
Model.where(:id => 1..5).destroy_all

UPDATE

User.where(:id => params[:ids]).destroy_all

/users?ids[]=1&ids[]=2&ids[]=3

Solution 2 - Ruby on-Rails

Model.delete([1,2,5,6]) 

or

Model.delete_all(["col_name in (?)", [1,2,5,6]])

Just pass the ids array

Solution 3 - Ruby on-Rails

If performance is important to you and/or if you work on a large dataset you should prefer delete_all over destroy_all.

Destroy_all will execute a DELETE query one at a time. So it can be very slow. More details about the differences between delete_all and destroy_all can be found on this page.

Since the @M Kumar's answer will be deprecated with the new rail's version.

Model.delete_all(["col_name in (?)", [1,2,5,6]])
DEPRECATION WARNING: Passing conditions to delete_all is deprecated and will be removed in Rails 5.1.

This command might help other's in the future :

Model.where(id: [1,2,5,6]).delete_all

Solution 4 - Ruby on-Rails

You can also delete for a range of Ids. Say you have 1500 records and you want to delete from 751 to last:

a = Model.where(id: [751..1500])
a.destroy_all

Solution 5 - Ruby on-Rails

I had exactly the same problem, but the solution here did not work for me in rails 5.1.6.

Perhaps you pass parameter params[:ids] in the wrong way.

Here's how I fix it.

Before

Model.where(:id => params[:ids]).destroy_all

After

ids = params[:ids].split(",")
Model.where(:id => ids).destroy_all

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
QuestionCyberView Question on Stackoverflow
Solution 1 - Ruby on-RailsEugene RourkeView Answer on Stackoverflow
Solution 2 - Ruby on-RailsSachin RView Answer on Stackoverflow
Solution 3 - Ruby on-RailsdevohView Answer on Stackoverflow
Solution 4 - Ruby on-RailsLordKizView Answer on Stackoverflow
Solution 5 - Ruby on-Rails蔡依玲View Answer on Stackoverflow