Flowdock
method

find_each

Importance_3
v2.3.8 - Show latest stable - 3 notes - Class: ActiveRecord::Batches::ClassMethods
find_each(options = {}) public

Yields each record that was found by the find options. The find is performed by find_in_batches with a batch size of 1000 (or as specified by the :batch_size option).

Example:

  Person.find_each(:conditions => "age > 21") do |person|
    person.party_all_night!
  end

Note: This method is only intended to use for batch processing of large amounts of records that wouldn’t fit in memory all at once. If you just need to loop over less than 1000 records, it’s probably better just to use the regular find methods.

Show source
Register or log in to add new notes.
September 9, 2009
3 thanks

Will discard any order option

order_by(:created_at).find_each == FAIL!!!

class ActiveRecord::Base
  # normal find_each does not use given order but uses id asc
  def self.find_each_with_order(options={})
    raise "offset is not yet supported" if options[:offset]

    page = 1
    limit = options[:limit] || 1000

    loop do
      offset = (page-1) * limit
      batch = find(:all, options.merge(:limit=>limit, :offset=>offset))
      page += 1

      batch.each{|x| yield x }

      break if batch.size < limit
    end
  end
end
November 12, 2009
2 thanks

You can't use the :limit option either

Person.find_each(:limit => 10000)…

Will result in:

RuntimeError: You can’t specify a limit, it’s forced to be the batch_size

January 10, 2012
2 thanks

Will discard :select

Only does

SELECT model.id FROM models_table

regardless of select options