Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Browse files

fix `first` for paginated AR Relations

Fixes #223
  • Loading branch information...
commit 6d35492963eb2e8fb6683120112cb65afaae513d 1 parent 25582e5
@mislav authored
11 lib/will_paginate/active_record.rb
@@ -39,6 +39,17 @@ def limit(num)
+ # dirty hack to enable `first` after `limit` behavior above
+ def first(*args)
+ if current_page
+ rel = clone
+ rel.current_page = nil
+ rel.first(*args)
+ else
+ super
+ end
+ end
def offset(value = nil)
if value.nil? then offset_value
else super(value)
12 spec/finders/active_record_spec.rb
@@ -92,6 +92,18 @@
rel.offset.should == 6
+ it "supports #first" do
+ rel = Developer.order('id').page(2).per_page(4)
+ rel.first.should == users(:dev_5)
+ rel.first(2).should == users(:dev_5, :dev_6)
+ end
+ it "supports #last" do
+ rel = Developer.order('id').page(2).per_page(4)
+ rel.last.should == users(:dev_8)
+ == users(:poor_jamis)
+ end
it "keeps pagination data after 'scoped'" do
rel =
rel.per_page.should == 10

1 comment on commit 6d35492


This seems to be triggering a new query when using page_entries_info with a collection association, since it uses collection.first.class. Now first is creating a cloned relation, which does not contain the loaded flag and thus a new query is created for finding the first record.

A workaround that seems to be working is to call to_a in the collection:

def page_entries_info(collection, *args)
  super collection.to_a, *args

This seems to have eliminated the extra query problem as far as I could se, but I'm not sure if there's a best solution right now.

Please sign in to comment.
Something went wrong with that request. Please try again.