Ruby-on-rails 如何在 Rails 3 中同时销毁多个对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14434071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:18:42  来源:igfitidea点击:

How to Destroy multiple objects simultaneously in Rails 3

ruby-on-railsruby-on-rails-3

提问by Cyber

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

我有一个 Rails 应用程序试图一次删除多个对象。

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.

我曾尝试将一组由 ',' 分隔的 id 发送到 rails destroy 方法,但它只销毁单个对象。是否可以删除rails 3中的多个对象。

回答by Eugene Rourke

destroy_alldestroys the records matching conditions by calling destroy methodfor each instantiating record. So object's callbacks are executed.

destroy_all通过为每个实例化记录调用destroy 方法销毁符合条件的记录。所以对象的回调被执行。

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

回答by Sachin R

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

or

或者

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

Just pass the ids array

只需传递 ids 数组

回答by devoh

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

如果性能对您很重要和/或如果您处理大型数据集,您应该更喜欢 delete_all 而不是 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.

Destroy_all 将一次执行一个 DELETE 查询。所以它可能会很慢。可以在此页面上找到有关delete_all 和 destroy_all 之间差异的更多详细信息。

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

由于@M Kumar 的答案将在新轨道的版本中被弃用。

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

回答by LordKiz

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

您还可以删除一系列 ID。假设您有 1500 条记录,并且想要从 751 删除到最后一条:

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

回答by u6586967

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

我遇到了完全相同的问题,但是这里的解决方案在 Rails 5.1.6 中对我不起作用。

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

也许您params[:ids]以错误的方式传递参数。

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