From 5a40939e4b63ea009a4ba9edaf52f32790e188a0 Mon Sep 17 00:00:00 2001 From: Florent Piteau Date: Tue, 26 Apr 2011 16:58:34 +0200 Subject: [PATCH] Only remove includes from count if they are irrelevant. --- .../models/active_record_relation_methods.rb | 5 ++++- spec/models/active_record_relation_methods_spec.rb | 12 +++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/kaminari/models/active_record_relation_methods.rb b/lib/kaminari/models/active_record_relation_methods.rb index 7015181..ba8f52a 100644 --- a/lib/kaminari/models/active_record_relation_methods.rb +++ b/lib/kaminari/models/active_record_relation_methods.rb @@ -12,8 +12,11 @@ module Kaminari def total_count #:nodoc: # #count overrides the #select which could include generated columns referenced in #order, so skip #order here, where it's irrelevant to the result anyway - c = except(:offset, :limit, :includes, :order).count + c = except(:offset, :limit, :order) + # Remove includes only if they are irrelevant + c = c.except(:includes) unless references_eager_loaded_tables? # .group returns an OrderdHash that responds to #count + c = c.count c.respond_to?(:count) ? c.count : c end end diff --git a/spec/models/active_record_relation_methods_spec.rb b/spec/models/active_record_relation_methods_spec.rb index a321805..c0956fa 100644 --- a/spec/models/active_record_relation_methods_spec.rb +++ b/spec/models/active_record_relation_methods_spec.rb @@ -4,7 +4,11 @@ describe Kaminari::ActiveRecordRelationMethods do describe '#total_count' do before do @author = User.create! :name => 'author' - @books = 2.times.map { @author.books_authored.create! } + @author2 = User.create! :name => 'author2' + @author3 = User.create! :name => 'author3' + @books = 2.times.map {|i| @author.books_authored.create!(:title => "title%03d" % i) } + @books2 = 3.times.map {|i| @author2.books_authored.create!(:title => "title%03d" % i) } + @books3 = 4.times.map {|i| @author3.books_authored.create!(:title => "subject%03d" % i) } @readers = 4.times.map { User.create! :name => 'reader' } @books.each {|book| book.readers << @readers } end @@ -14,5 +18,11 @@ describe Kaminari::ActiveRecordRelationMethods do @author.readers.by_read_count.page(1).total_count.should == @readers.size end end + context "when the scope use conditions on includes" do + it "should keep includes and successfully count the results" do + # Only @author and @author2 have books titled with the title00x partern + User.includes(:books_authored).where("books.title LIKE 'title00%'").page(1).total_count.should == 2 + end + end end end