How to Destroy multiple objects simultaneously in Rails 3

后端 未结 5 457
慢半拍i
慢半拍i 2020-12-13 23:13

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

相关标签:
5条回答
  • 2020-12-13 23:51

    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
    
    0 讨论(0)
  • 2020-12-13 23:54

    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
    
    0 讨论(0)
  • 2020-12-13 23:57
    Model.delete([1,2,5,6]) 
    

    or

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

    Just pass the ids array

    0 讨论(0)
  • 2020-12-14 00:03

    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
    
    0 讨论(0)
  • 2020-12-14 00:05

    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
    
    0 讨论(0)
提交回复
热议问题