Thomas Fuchs
Hi, I'm Thomas Fuchs. I'm the author of Zepto.js, of script.aculo.us, and I'm a Ruby on Rails core alumnus. With Amy Hoy I'm building cheerful software, like Noko Time Tracking and Every Time Zone and write books like Retinafy.me.
   Want me to speak at your conference? Contact me!

ActiveRecord, eager loading, and SQL LIMIT/OFFSET

June 12th, 2005

The eager loading of associations that where first introduced in Rails 0.12.0 suffer from one drawback: It’s not possible to specify :limit or :offset on ActiveRecord’s find method.

Here’s a way to work around this, by using an SQL subquery to select the correct ids:


page = 1
per_page = 25
limit = "LIMIT #{per_page} OFFSET #{(page-1)*per_page}"
stuff = Sometable.find(:all,
  :conditions =>
     "sometable.id IN (SELECT id FROM sometable #{limit})",
  :include => [:someassoc, :someotherassoc])

This code works fine with PostgreSQL, as it is my database of choice. Your mileage with other databases may vary.