61

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.

abagshaw
  • 6,162
  • 4
  • 38
  • 76
Cyber
  • 4,844
  • 8
  • 41
  • 61
  • 2
    The answer has given is correct, but just for knowledge go through the difference of delete_all and destroy_all. This would help you : http://stackoverflow.com/questions/6698207/delete-all-vs-destroy-all – Anand Soni Jan 21 '13 at 07:57

5 Answers5

129

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
Eugene Rourke
  • 4,934
  • 1
  • 22
  • 24
8
Model.delete([1,2,5,6]) 

or

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

Just pass the ids array

Sachin R
  • 11,606
  • 10
  • 35
  • 40
2

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
蔡依玲
  • 21
  • 3
0

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
devoh
  • 867
  • 9
  • 13
0

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
LordKiz
  • 603
  • 6
  • 15