ActiveRecord, eager loading, and SQL LIMIT/OFFSET
June 12th, 2005The 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.
Tweet