method

find_in_batches

Importance_3
v2.3.8 - Show latest stable - 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.8 (0)
  • 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.0.0.1
  • 5.1.7
  • 5.2.3
  • 6.0.0
  • 6.1.3.1
  • 6.1.7.7
  • 7.0.0
  • 7.1.3.2
  • 7.1.3.4
  • What's this?
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.

Example:

  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! }
  end
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|
    person.send_presents_to(birthday_childs)
  end
end

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|
  peeps.reject!(&:bad?)
  # ... more operations on peeps
  puts 'Tick'
end

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'
end

You should see Tick outputted 3 times