find_in_batchesメソッド

Railscasts - Rails 2.3 Extras

findする件数を小分けにしてくれるメソッド。
こんなのがあるとは知らなかった。
まさにバッチ用。

使い方

:batch_size オプションで件数を指定。selectしてupdateなど。

Product.find_in_batches(:batch_size => 10) do |batch|
  puts "Products in batch: #{batch.size}"
end

ソース

.gem/ruby/1.8/gems/activerecord-2.3.10/lib/active_record/batches.rb

      def find_in_batches(options = {})
        raise "You can't specify an order, it's forced to be #{batch_order}" if options[:order]
        raise "You can't specify a limit, it's forced to be the batch_size"  if options[:limit]

        start = options.delete(:start).to_i
        batch_size = options.delete(:batch_size) || 1000

        proxy = scoped(options.merge(:order => batch_order, :limit => batch_size))
        records = proxy.find(:all, :conditions => [ "#{table_name}.#{primary_key} >= ?", start ])

        while records.any?
          yield records

          break if records.size < batch_size
          
          last_value = records.last.id
          
          raise "You must include the primary key if you define a select" unless last_value.present?
          
          records = proxy.find(:all, :conditions => [ "#{table_name}.#{primary_key} > ?", last_value ])
        end
      end