views:

94

answers:

3

I'm working with some complex queries using the dynamic find_all method and reached to a point where sending a block to that find_all method would really simplify my code.

Is there any plugin or work in-progress dealing with this?

In simple terms, I'd like to do something like:

@products = Product.find_all_by_ids(ids, .....) do |p|
            # do something to each product like      
            p.stock += 10
          end

Obviously, any other guide or better way of doing this would be greatly appreciated.

+2  A: 

I use the .each method which Enumerable provides like

@products = Product.find_all_by_ids(ids, .....)
@products.each { |p| p.stock += 10 }

There are even some extensions to Enumerable that Rails provides that might help you a bit if you're doing some common stuff.

Also, don't forget to save your objects with something like p.save if you want the changes to actually persist.

jamuraa
Thanks, but this is the actual approach I was using. However, my concern was wondering if there was a way to send it a block to do that kind of calculations.Using two statements seemed a bit forceful
Yaraher
+2  A: 

Rails 2.3 introduced the find_in_batches and find_each methods (see here) for batch processing of many records.

You can thus do stuff like:

  Person.find_each(:conditions => "age > 21") do |person|
    person.party_all_night!
  end
JRL
Nice find, I had read about this before but didn't recall it. Thanks!
Yaraher
A: 

What's wrong with this:

@products = Product.find_all_by_ids(ids).each do |p| 
  p.stock+=10
 end

In case you didn't know, each returns the array passed to it.

EmFi