Fix #count on a has_many :through association so that it recognizes the :uniq option. Closes #8801 [lifofifo]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@7199 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
This commit is contained in:
Rick Olson 2007-07-20 00:10:06 +00:00
parent 9014bf3f26
commit 3029a76af3
3 changed files with 22 additions and 1 deletions

View File

@ -1,5 +1,7 @@
*SVN*
* Fix #count on a has_many :through association so that it recognizes the :uniq option. Closes #8801 [lifofifo]
* Fix and properly document/test count(column_name) usage. Closes #8999 [lifofifo]
* Remove deprecated count(conditions=nil, joins=nil) usage. Closes #8993 [lifofifo]

View File

@ -101,6 +101,16 @@ module ActiveRecord
calculate(:sum, *args, &block)
end
def count(*args)
column_name, options = @reflection.klass.send(:construct_count_options_from_args, *args)
if @reflection.options[:uniq]
# This is needed becase 'SELECT count(DISTINCT *)..' is not valid sql statement.
column_name = "#{@reflection.klass.table_name}.#{@reflection.klass.primary_key}" if column_name == :all
options.merge!(:distinct => true)
end
@reflection.klass.send(:with_scope, construct_scope) { @reflection.klass.count(column_name, options) }
end
protected
def method_missing(method, *args, &block)
if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))

View File

@ -31,6 +31,15 @@ class AssociationsJoinModelTest < Test::Unit::TestCase
assert_equal 1, authors(:mary).unique_categorized_posts.size
end
def test_has_many_uniq_through_count
author = authors(:mary)
assert !authors(:mary).unique_categorized_posts.loaded?
assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count }
assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count(:title) }
assert_queries(1) { assert_equal 0, author.unique_categorized_posts.count(:title, :conditions => "title is NULL") }
assert !authors(:mary).unique_categorized_posts.loaded?
end
def test_polymorphic_has_many
assert posts(:welcome).taggings.include?(taggings(:welcome_general))
end