From 9500ad5fbc337d881dc953631f6d808ad08774c1 Mon Sep 17 00:00:00 2001 From: Michael Koziarski Date: Sun, 27 Jan 2008 02:41:55 +0000 Subject: Make sure count works on has_many :through associations using :group. Closes #10480 [remvee] git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@8742 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- activerecord/lib/active_record/associations.rb | 6 ++++++ .../active_record/associations/has_many_through_association.rb | 9 +++++++++ 2 files changed, 15 insertions(+) (limited to 'activerecord/lib/active_record') diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index cb17b6e483..a1c8bd6e50 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -55,6 +55,12 @@ module ActiveRecord end end + class HasManyThroughCantCountOnColumnForGroupedAssociation < ActiveRecordError #:nodoc: + def initialize(owner, reflection, column_name) + super("Cannot count on column '#{column_name}' for association '#{owner.class.name}##{reflection.name}' grouped by '#{reflection.options[:group]}'.") + end + end + class EagerLoadPolymorphicError < ActiveRecordError #:nodoc: def initialize(reflection) super("Can not eagerly load the polymorphic association #{reflection.name.inspect}") diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index 1ca44d645c..96d0b73da2 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -124,6 +124,15 @@ module ActiveRecord column_name = "#{@reflection.quoted_table_name}.#{@reflection.klass.primary_key}" if column_name == :all options.merge!(:distinct => true) end + + if @reflection.options[:group] + unless column_name == :all + raise HasManyThroughCantCountOnColumnForGroupedAssociation.new(@owner, @reflection, column_name) + end + column_name = @reflection.options[:group] + options.merge!(:distinct => true) + end + @reflection.klass.send(:with_scope, construct_scope) { @reflection.klass.count(column_name, options) } end -- cgit v1.2.3