Flowdock
method

find_each

Importance_3
Ruby on Rails latest stable (v6.1.7.7) - 3 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
  • 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 v6.1.7.7:

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