Rails find_each or find_in_batches methods are looping through a collection of records from the database.
This batch processing methods allow us to work with the records in batches, thereby greatly reducing memory consumption.
Person.find_each(:conditions => "age > 21") do |person|
person.party_all_night!
end
But major drawback with these methods is - ordering/sorting the records by primary key id, hence we cannot specify our own order_by.
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
Like this:
Like Loading...
Related
Leave a Reply