2017-08-08 126 views
0

我正在使用Rails 5.我想從表中刪除一堆記錄。我有什麼是刪除模型對象數組的最快方法?

currencies = CryptoCurrency.order('latest_market_cap_in_usd desc').limit(num_currencies) 
current_index_currencies = CryptoIndexCurrency.all.pluck(:crypto_currency_id) 

currencies_to_remove = current_index_currencies - currencies 
... 
currencies_to_remove.each do |currency| 
    currency.destroy 
end 

其中「currencies_to_remove」應該包含所有我要刪除的模型的數組。但我遍歷列表

2.4.0 :005 > svc.create_index 
    (0.4ms) SELECT "crypto_index_currencies"."crypto_currency_id" FROM "crypto_index_currencies" 
    CryptoCurrency Load (1.5ms) SELECT "crypto_currencies".* FROM "crypto_currencies" ORDER BY latest_market_cap_in_usd desc LIMIT $1 [["LIMIT", 12]] 
NoMethodError: undefined method `destroy' for 1020:Integer 
    from /Users/davea/.rvm/gems/ruby-2.4.0/gems/whenever-0.9.7/lib/whenever/numeric.rb:10:in `method_missing' 
    from /Users/davea/Documents/workspace/cindex/app/services/crypto_index_service.rb:17:in `block in create_index' 
    from /Users/davea/Documents/workspace/cindex/app/services/crypto_index_service.rb:16:in `each' 
    from /Users/davea/Documents/workspace/cindex/app/services/crypto_index_service.rb:16:in `create_index' 
    from (irb):5 
    from /Users/davea/.rvm/gems/ruby-2.4.0/gems/railties-5.0.4/lib/rails/commands/console.rb:65:in `start' 
    from /Users/davea/.rvm/gems/ruby-2.4.0/gems/railties-5.0.4/lib/rails/commands/console_helper.rb:9:in `start' 

回答

3

這是因爲currencies_to_remove包含模型的索引中刪除,而不是模型時,得到下面的錯誤。因此,destroy方法未定義。

刪除它們最快的方式將是delete方法的模型類:

CryptoCurrency.delete(currencies_to_remove) 

但是如果你需要調用銷燬回調,則可能需要destroy方法:

CryptoCurrency.destroy(currencies_to_remove) 

請注意,如果未找到指定數組中的任何記錄,則destroy方法將引起RecordNotFound異常

相關問題