Delete object from array of active record

In Rails, I have the following Active Record collection:

@products = Product.all 

I need to skip this collection and remove some objects from it without deleting them from the database. Therefore, using

 @products.each do |product| if CONDITION product.delete end end 

It will not work, as it will also remove the product from the database. Is there a way to remove certain products from this collection without deleting them from the database?

+7
ruby-on-rails
source share
2 answers

The first question is, if you do not need all the records, then why even return them from the database? Why not use the where clause to filter the results:

@products = Product.where(<CONDITIONS>)

Secondly, if you insist on returning all the results and then filtering, use the .reject block:

@products = Product.all.reject { |p| <CONDITION> }

+10
source share

Since Active Records Collection 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.

+1
source share

All Articles