Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails, how do I delete all the objects in an array?

I am using Rails 5 and I want to delete an array of objects. In a previous thread, I read "destroy_all" was the truth and the light. I had two arrays of objects, which I subtract to get a third array

  unused_currencies = all_currencies - currencies_from_feed
  unused_currencies.destroy_all

but when using destroy_all I got this error:

NoMethodError: undefined method `destroy_all' for #<Array:0x007feea8878770>
like image 566
Dave Avatar asked Jan 20 '26 18:01

Dave


1 Answers

This code will make a single SQL query:

unused_currencies = all_currencies - currencies_from_feed
CurrencyModel.delete(unused_currencies)

where CurrencyModel is the model of your currencies.

You might want to use destroy if you need to run callbacks on the models:

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

This code will make a number of queries proportional to the number of unused currencies

like image 63
Igor Drozdov Avatar answered Jan 22 '26 11:01

Igor Drozdov