From 723affb1757867e15624badce158caaa582a8b25 Mon Sep 17 00:00:00 2001 From: oleg dashevskii Date: Tue, 31 Aug 2010 23:49:31 +0700 Subject: [PATCH] A brute-force fix for #5441 --- .../lib/active_record/relation/calculations.rb | 6 +++++- activerecord/test/cases/calculations_test.rb | 12 +++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index ab78067..1290a95 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -211,7 +211,11 @@ module ActiveRecord select_statement = if operation == 'count' && column_name == :all "COUNT(*) AS count_all" else - Arel::Attribute.new(@klass.unscoped, column_name).send(operation).as(aggregate_alias).to_sql + if @klass.column_names.include?(column_name.to_s) + Arel::Attribute.new(@klass.unscoped, column_name).send(operation).as(aggregate_alias).to_sql + else + Arel::SqlLiteral.new(column_name == :all ? "*" : column_name.to_s).send(operation).as(aggregate_alias).to_sql(Arel::Sql::SelectClause.new(@klass.send(:relation))) + end end select_statement << ", #{group_field} AS #{group_alias}" diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index afef313..7ec4090 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -275,6 +275,17 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal 2, Account.count(:firm_id, :conditions => "credit_limit = 50 AND firm_id IS NOT NULL") end + def test_should_count_field_in_joined_table + assert_equal 5, Account.count('companies.id', :joins => :firm) + assert_equal 4, Account.count('companies.id', :joins => :firm, :distinct => true) + end + + def test_should_count_field_in_joined_table_with_group_by + c = Account.count('companies.id', :group => 'accounts.firm_id', :joins => :firm) + + [1,6,2,9].each { |firm_id| assert c.keys.include?(firm_id) } + end + def test_count_with_no_parameters_isnt_deprecated assert_not_deprecated { Account.count } end @@ -335,5 +346,4 @@ class CalculationsTest < ActiveRecord::TestCase def test_from_option_with_table_different_than_class assert_equal Account.count(:all), Company.count(:all, :from => 'accounts') end - end -- 1.7.2.2