7

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?

2
  • 2
    Feel free to disregard this, but this is against anything such ORMs are for. ActiveRecotrd is supposed to represent the objects in the database. I recommend you rethink your entire approach - do you really have a good reason for such a hack? Commented Dec 16, 2014 at 18:21
  • Probably not, but I need to loop through another array as well and compare objects in both arrays to each other. I'm not sure how I would go about fitting that logic into a statement like @products = Product.where(<CONDITIONS>) Commented Dec 16, 2014 at 18:37

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

11 Comments

Thanks! I need to nest a loop through another array and compare each object in that array to each object in this array as part of the condition. I wasn't sure how I could accomplish that within @products = Product.where(<CONDITIONS>)
@Arw50452 is the comparison array and array of values (i.e. [1,2,3,4]) or an array of hashes (i.e. [{value: 1}, {value: 2}, {value: 3}])?
The comparison array is another Active Record Array
Do you care to expand on your use case? I have a feeling that there is a really simple solution to your problem.
Sure! I have two arrays 1) products 2) requests. The relevant fields in the requests array are: status, requestor_productid, requestee_productid, requestor_userid, and requestee_userid. If all of the following conditions are met for any given product, I want it removed from the products array
|
2

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.

2 Comments

I get undefined method 'reject' when trying reject on my Active Record Collection. Also tried reject! with same result.
@ChaosFreak can you show us the complete error message?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.