在Rails中,如何删除数组中的所有对象?

问题描述:

我正在使用Rails 5,我想删除一组对象。在之前的一篇文章中,我读到“destroy_all”是真相​​和光明。我有对象的两个数组,我减去获得的第三阵列在Rails中,如何删除数组中的所有对象?

unused_currencies = all_currencies - currencies_from_feed 
    unused_currencies.destroy_all 

但使用destroy_all当我得到这个错误:

NoMethodError: undefined method `destroy_all' for #<Array:0x007feea8878770> 
+0

什么定义'currency_from_feed'假设'all_currencies'实际上是'Currency.all',可能有一个干净的范围可以写成处理“unused_currencies”的集合,然后它很简单'Currency.unused_currencies.destroy_all'但没有额外的信息,它将很难帮助 – engineersmnky

此代码将使单个SQL查询:

unused_currencies = all_currencies - currencies_from_feed 
CurrencyModel.delete(unused_currencies) 

其中CurrencyModel是您的货币的型号。

你可能想,如果你需要在模型上运行的回调使用destroy

unused_currencies = all_currencies - currencies_from_feed 
CurrencyModel.destroy(unused_currencies.map(&:id)) 

此代码将使数成正比,未使用的货币

Destroy_all是主动 - 记录类型的东西。

你究竟想要做什么?如果你只是想摆脱数组,你可以用

unused_currencies = []

如果你想消灭一堆的活动记录对象的你将不得不遍历数组中重写它它并单独删除每个对象。

destroy_all作品为ActiveRecord::Relation

如果你想清除数组,你可以这样做:unused_currencies = []

如果你想删除的每个项目在数组中: unused_currencies.each(&:destroy)。这将生成每个项目的删除查询。

要删除所有对象一次(假设它们都属于同一个模型,这将炸毁你的脸,如果他们不这样做!)

unused_currencies.first.class.destroy_all(unused_currencies.map(&:id)) 
+0

对不起,我不想清除数组,我想从数据库中删除数组中的所有对象。 – Dave

+0

@Dave然后使用第二个 – Ruslan

+0

将创建多少个SQL语句?是否有可能在一个SQL语句中删除所有内容? – Dave

数量的查询如果您使用map ,你在内存中加载所有数据。我认为你可以这样做:

all_currencies.where.not(id: currencies_from_feed.select(:id)).destroy_all 

如果all_currenciescurrencies_from_feed的ActiveRecord ::关系,这将产生只有一个请求SQL