Ruby on Rails latest stable (v5.2.3) - 2 notes - Class: ActiveRecord::Batches::ClassMethods
  • 1.0.0
  • 1.1.6
  • 1.2.6
  • 2.0.3
  • 2.1.0
  • 2.2.1
  • 2.3.2 (0)
  • 2.3.8 (1)
  • 3.0.0
  • 3.0.9
  • 3.1.0
  • 3.2.1
  • 3.2.8
  • 3.2.13
  • 4.0.2
  • 4.1.8
  • 4.2.1
  • 4.2.7
  • 4.2.9
  • 5.1.7
  • 5.2.3
  • What's this?

Method deprecated or moved

This method is deprecated or moved on the latest stable version. The last existing version (v2.3.8) is shown here.

These similar methods exist in v5.2.3:

find_in_batches(options = {}) public

Yields each batch of records that was found by the find options as an array. The size of each batch is set by the :batch_size option; the default is 1000.

You can control the starting point for the batch processing by supplying the :start option. This is especially useful if you want multiple workers dealing with the same processing queue. You can make worker 1 handle all the records between id 0 and 10,000 and worker 2 handle from 10,000 and beyond (by setting the :start option on that worker).

It’s not possible to set the order. That is automatically set to ascending on the primary key ("id ASC") to make the batch ordering work. This also mean that this method only works with integer-based primary keys. You can’t set the limit either, that’s used to control the the batch sizes.


  Person.find_in_batches(:conditions => "age > 21") do |group|
    sleep(50) # Make sure it doesn't get too crowded in there!
    group.each { |person| person.party_all_night! }
Show source
Register or log in to add new notes.
November 13, 2009
1 thank

Careful with scopes

Just like find, find_in_batches introduces an implicit scope into the block. So for example

Person.find_in_batches(:conditions => {:birthday => Date.today}) do |birthday_childs|
  Person.all.each do |person|

does not work as expected, because the Person.all within the block will also find only persons with :conditions => {:birthday => Date.today}.

January 27, 2011
1 thank

Dont reject! on the yielded batch

If you remove any values from the batch, the while loop in find_in_batches breaks even if there are additional batches:

People.count # => 3000

People.find_in_batches do |peeps|
  # ... more operations on peeps
  puts 'Tick'

Running the above code, you’ll only see Tick once. Rather use:

People.find_in_batches do |peeps|
  peeps = peeps.reject(&:bad?)
  # ... more operations on peeps
  puts 'Tick'

You should see Tick outputted 3 times