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.
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.
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
Model.delete([1,2,5,6])
or
Model.delete_all(["col_name in (?)", [1,2,5,6]])
Just pass the ids array
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.
Model.where(:id => params[:ids]).destroy_all
ids = params[:ids].split(",")
Model.where(:id => ids).destroy_all
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
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