From 7df10895cfd6a8b4af6ca8b4b88a7a8e30d9be14 Mon Sep 17 00:00:00 2001 From: David Cuddeback Date: Fri, 4 Feb 2011 12:04:43 -0800 Subject: [PATCH] fix count with scoped select --- activerecord/lib/active_record/calculations.rb | 2 +- activerecord/test/cases/calculations_test.rb | 20 +++++++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index f6249e5..8a9342c 100644 --- a/activerecord/lib/active_record/calculations.rb +++ b/activerecord/lib/active_record/calculations.rb @@ -140,7 +140,7 @@ module ActiveRecord protected def construct_count_options_from_args(*args) options = {} - column_name = :all + column_name = scope(:find, :select) || :all # We need to handle # count() diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index d5bb358..56a8fb8 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -1,4 +1,6 @@ require "cases/helper" +require 'models/author' +require 'models/post' require 'models/company' require 'models/topic' require 'models/edge' @@ -15,7 +17,7 @@ class NumericData < ActiveRecord::Base end class CalculationsTest < ActiveRecord::TestCase - fixtures :companies, :accounts, :topics, :owners, :pets, :toys + fixtures :companies, :accounts, :topics, :owners, :pets, :toys, :authors, :posts def test_should_sum_field assert_equal 318, Account.sum(:credit_limit) @@ -285,6 +287,22 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal 4, Account.count(:distinct => true, :include => :firm, :select => :credit_limit) end + def test_should_count_scoped_select + Account.update_all("credit_limit = 50") + assert_equal 1, Account.scoped(:select => "DISTINCT credit_limit").count + end + + def test_should_count_scoped_select_with_options + Account.update_all("credit_limit = 50") + Account.first.update_attribute('credit_limit', 49) + assert_equal 1, Account.scoped(:select => "DISTINCT credit_limit").count(:conditions => [ 'credit_limit >= 50'] ) + end + + def test_should_count_scoped_select_on_association + author = Author.first + assert_equal author.posts.count, author.posts.scoped(:conditions => "1=1").count + end + def test_should_count_manual_select_with_include assert_equal 6, Account.count(:select => "DISTINCT accounts.id", :include => :firm) end -- 1.7.3.5