Permalink
Browse files

Merge 8801 fix to stable. Closes #8801

git-svn-id: http://svn-commit.rubyonrails.org/rails/branches/1-2-stable@7347 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
1 parent 1dd0034 commit 19dff148149e9679b4d9f46cf8774a0b2d77b0a7 @NZKoz NZKoz committed Aug 20, 2007
View
@@ -1,5 +1,7 @@
*SVN*
+* Fix #count on a has_many :through association so that it recognizes the :uniq option. Closes #8801 [lifofifo]
+
* Don't clobber includes passed to has_many.count [danger]
* Make sure has_many uses :include when counting [danger]
@@ -101,6 +101,16 @@ def create!(attrs = nil)
def sum(*args, &block)
calculate(:sum, *args, &block)
end
+
+ def count(*args)
+ column_name, options = @reflection.klass.send(:construct_count_options_from_legacy_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)
@@ -29,7 +29,16 @@ def test_has_many_uniq_through_join_model
assert_equal 2, authors(:mary).categorized_posts.size
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

0 comments on commit 19dff14

Please sign in to comment.