Sending a code block to a find_all dynamic method
I am working with some complex q开发者_开发技巧ueries 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
Any other guide or better way of doing this would be greatly appreciated.
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
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. 
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.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论