2017-08-09 57 views
-1

我正在使用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

回答

1

此代碼將使單個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)) 

此代碼將使數成正比,未使用的貨幣

0

Destroy_all是主動 - 記錄類型的東西。

你究竟想要做什麼?如果你只是想擺脫數組,你可以用

unused_currencies = []

如果你想消滅一堆的活動記錄對象的你將不得不遍歷數組中重寫它它並單獨刪除每個對象。

0

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

0

數量的查詢如果您使用map ,你在內存中加載所有數據。我認爲你可以這樣做:

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

如果all_currenciescurrencies_from_feed的ActiveRecord ::關係,這將產生只有一個請求SQL

相關問題