From 73e721c20b9ea80fa4747ec23783c6bf991034f9 Mon Sep 17 00:00:00 2001 From: Nobuhiro IMAI Date: Sat, 11 Apr 2009 14:55:10 +0900 Subject: [PATCH] fix ActiveRecord::Base.count with scoped :from option --- activerecord/lib/active_record/calculations.rb | 5 +++-- activerecord/test/cases/calculations_test.rb | 5 +++++ activerecord/test/models/developer.rb | 1 + 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index f077818..8c75b45 100644 --- a/activerecord/lib/active_record/calculations.rb +++ b/activerecord/lib/active_record/calculations.rb @@ -196,8 +196,9 @@ module ActiveRecord sql = "SELECT COUNT(*) AS #{aggregate_alias}" if use_workaround sql << ", #{options[:group_field]} AS #{options[:group_alias]}" if options[:group] - if options[:from] - sql << " FROM #{options[:from]} " + from = options[:from] || (scope && scope[:from]) + if from + sql << " FROM #{from} " else sql << " FROM (SELECT #{distinct}#{column_name}" if use_workaround sql << " FROM #{connection.quote_table_name(table_name)} " diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 56dcdea..731aaea 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -309,6 +309,11 @@ class CalculationsTest < ActiveRecord::TestCase Company.count(:type, :conditions => {:type => "Firm"}, :from => 'companies') end + def test_count_with_scoped_from_option + assert_equal 3, Developer.salary_top3.count + assert_equal 0, Developer.salary_top3.count(:conditions => {:salary => 80000}) + end + def test_sum_with_from_option assert_equal Account.sum(:credit_limit), Account.sum(:credit_limit, :from => 'accounts') assert_equal Account.sum(:credit_limit, :conditions => "credit_limit > 50"), diff --git a/activerecord/test/models/developer.rb b/activerecord/test/models/developer.rb index 92039a4..265f4df 100644 --- a/activerecord/test/models/developer.rb +++ b/activerecord/test/models/developer.rb @@ -44,6 +44,7 @@ class Developer < ActiveRecord::Base has_many :audit_logs named_scope :jamises, :conditions => {:name => 'Jamis'} + named_scope :salary_top3, :from => "(#{construct_finder_sql(:order => "#{quoted_table_name}.salary DESC", :limit => 3)}) AS #{quoted_table_name}" validates_inclusion_of :salary, :in => 50000..200000 validates_length_of :name, :within => 3..20 -- 1.6.2.2