From 565afd93e7fd970d9a69fc33096fbf45de457695 Mon Sep 17 00:00:00 2001 From: Manfred Stienstra Date: Tue, 10 Mar 2009 15:32:36 +0100 Subject: [PATCH] Filter the count column on :select options coming from associations to make them work on MySQL 5.1 and Sqlite3. --- activerecord/lib/active_record/calculations.rb | 10 +++++++--- .../has_many_through_associations_test.rb | 4 ++++ activerecord/test/models/tag.rb | 2 ++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index f077818..c10d88f 100644 --- a/activerecord/lib/active_record/calculations.rb +++ b/activerecord/lib/active_record/calculations.rb @@ -150,10 +150,10 @@ module ActiveRecord # selects specified by scopes case args.size when 0 - column_name = scope(:find)[:select] if scope(:find) + column_name = sanitize_column_for_count_options(scope(:find)[:select]) if scope(:find) when 1 if args[0].is_a?(Hash) - column_name = scope(:find)[:select] if scope(:find) + column_name = sanitize_column_for_count_options(scope(:find)[:select]) if scope(:find) options = args[0] else column_name = args[0] @@ -163,9 +163,13 @@ module ActiveRecord else raise ArgumentError, "Unexpected parameters passed to count(): #{args.inspect}" end - + [column_name || :all, options] end + + def sanitize_column_for_count_options(column) + (column =~ /^[`"]\w+[`"]\.\*$/) ? '*' : :all + end def construct_calculation_sql(operation, column_name, options) #:nodoc: operation = operation.to_s.downcase diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index c3ad0ee..aa40a1d 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -258,4 +258,8 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase def test_has_many_association_through_a_has_many_association_with_nonstandard_primary_keys assert_equal 1, owners(:blackbeard).toys.count end + + def test_count_through_has_many + assert_equal 1, posts(:welcome).tags.general.count + end end diff --git a/activerecord/test/models/tag.rb b/activerecord/test/models/tag.rb index a581b38..a3421f5 100644 --- a/activerecord/test/models/tag.rb +++ b/activerecord/test/models/tag.rb @@ -4,4 +4,6 @@ class Tag < ActiveRecord::Base has_one :tagging has_many :tagged_posts, :through => :taggings, :source => :taggable, :source_type => 'Post' + + named_scope :general, :conditions => { :name => 'General' } end \ No newline at end of file -- 1.6.1.3