Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Object from Active Record Array

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?

like image 993
Arw50452 Avatar asked Dec 16 '14 18:12

Arw50452


2 Answers

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> }

like image 157
tagCincy Avatar answered Oct 28 '22 12:10

tagCincy


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.

like image 34
Tamer Shlash Avatar answered Oct 28 '22 10:10

Tamer Shlash