How to handle a large set of ActiveRecord results in groups

I am wondering if there is a way to get an array of ActiveRecord results (or any array, for that matter) and process it in groups of 25 or so. Something like that:

User.all.each(25) do |group| # Some code that works with this group of 25 end 

I am just trying to avoid making multiple consecutive database queries. Thanks!

+4
source share
2 answers

Rails 2.3 has this feature. You can specify the batch_size parameter.

 User.find_in_batches(:batch_size =>25) do |group| # Some code that works with this group of 25 end 

You can find a good tutorial here . Please note that Rails will issue a request for every 25 entries. This is useful for maintaining low memory if you process a large number of records. If you want to split the results into multiple arrays, you can use in_groups_of , as suggested by Matt.

+21
source

All Articles