Active record find_each in batches

I wanted to iterate over an active record in batches. Found a great example but for my needs I wanted to walk backwards over the batch.

Needless to say it’s not possible. I don’t mind find_each limited to the id field, but DESC would be nice.

model.find_each(:batch_size => 200, :order => "DESC") do |instance|
  puts instance.inspect
end
# => You can't specify an order, it's forced to be model.id ASC

Significant Revisions

  • May 6th, 2024 Converted to jekyll markdown format and copied to personal site
  • Jan 13th, 2011 Originally published on txcowboycoder wordpress site1

Footnotes

Original Wordpress categories: [‘Ruby on Rails’]

Original Wordpress tags: “Ruby on Rails”, “find each”, “ruby active record”