Skip to content

Commit

Permalink
Active Record: enable overriding :total_entries value to avoid a coun…
Browse files Browse the repository at this point in the history
…t query

fixes mislav#143
  • Loading branch information
mislav committed Aug 2, 2011
1 parent 0b7a7a1 commit 5d26795
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/will_paginate/active_record.rb
Expand Up @@ -69,6 +69,7 @@ def total_entries
rel = self.except(*excluded)
# TODO: hack. decide whether to keep
rel = rel.apply_finder_options(@wp_count_options) if defined? @wp_count_options
@total_entries_queried = true
rel.count
end
end
Expand All @@ -90,7 +91,7 @@ def total_pages
def clone
other = super
other.current_page = current_page unless other.current_page
other.total_entries = nil
other.total_entries = nil if defined? @total_entries_queried
other
end

Expand Down Expand Up @@ -118,6 +119,7 @@ def paginate(options)
rel = limit(per_page).page(pagenum)
rel = rel.apply_finder_options(options) if options.any?
rel.wp_count_options = count_options if count_options
rel.total_entries = total.to_i unless total.blank?
rel
end

Expand Down
22 changes: 22 additions & 0 deletions spec/finders/active_record_spec.rb
Expand Up @@ -102,6 +102,28 @@
topics.total_entries.should == 0
}.should run_queries(1)
end

it "forgets count in sub-relations" do
lambda {
topics = Topic.paginate :page => 1, :per_page => 3
topics.total_entries.should == 4
topics.where('1 = 1').total_entries.should == 4
}.should run_queries(2)
end

it "overrides total_entries count with a fixed value" do
lambda {
topics = Topic.paginate :page => 1, :per_page => 3, :total_entries => 999
topics.total_entries.should == 999
# value is kept even in sub-relations
topics.where('1 = 1').total_entries.should == 999
}.should run_queries(0)
end

it "supports a non-int for total_entries" do
topics = Topic.paginate :page => 1, :per_page => 3, :total_entries => "999"
topics.total_entries.should == 999
end
end

it "should not ignore :select parameter when it says DISTINCT" do
Expand Down

0 comments on commit 5d26795

Please sign in to comment.