In Rails, I have the following Active Record Collection:
@products = Product.all
I need to loop through this collection and remove some objects from it without removing them from the database. Therefore, using
@products.each do |product|
if CONDITION
product.delete
end
end
Won't work, as this will also delete the product from the database. Is there a way to remove specific products from this collection without also deleting them from the database?
First question, if you don't want the all records, then why even return them from the DB? Why not use a where clause to filter results:
@products = Product.where(<CONDITIONS>)
Second, if you insist on returning all results then filtering, use a .reject
block:
@products = Product.all.reject { |p| <CONDITION> }
Since Active Record Collections are arrays, you can use reject!:
@products.reject! do |product|
// your_code
end
If your_code
evaluates to true
, then product
is removed from the collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With