ActiveRecord.find_each_with_order = find_each with order…

I just hate things that fail silently, just like User.order_by(:created_at).find_each

Which will simply ignore the order option….

So here comes the alternative…

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

(the 😮 is : and o)

Advertisements

2 thoughts on “ActiveRecord.find_each_with_order = find_each with order…

  1. It’s worth noting that the efficiencies gained by find_each for batch processing of large amounts of records are now lost. Also, WP is inserting a smiley in your code 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s