diff options
Diffstat (limited to 'activerecord')
-rw-r--r-- | activerecord/CHANGELOG | 2 | ||||
-rwxr-xr-x | activerecord/lib/active_record/base.rb | 2 | ||||
-rwxr-xr-x | activerecord/test/base_test.rb | 24 |
3 files changed, 25 insertions, 3 deletions
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index 8b5fc450f8..ade3e656a8 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* Added :select option to Base.count that'll allow you to select something else than * to be counted on. Especially important for count queries using DISTINCT #3839 [skaes] + * Correct syntax error in mysql DDL, and make AAACreateTablesTest run first [Bob Silva] * Allow :include to be used with has_many :through associations #3611 [Michael Schoen] diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index deb3c5fc1f..e040c86505 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -544,7 +544,7 @@ module ActiveRecord #:nodoc: def construct_counter_sql(options) sql = "SELECT COUNT(" sql << "DISTINCT " if options[:distinct] - sql << "#{table_name}.#{primary_key}) FROM #{table_name} " + sql << "#{options[:select] || "#{table_name}.#{primary_key}"}) FROM #{table_name} " sql << " #{options[:joins]} " if options[:joins] add_conditions!(sql, options[:conditions]) sql diff --git a/activerecord/test/base_test.rb b/activerecord/test/base_test.rb index 475e31028a..4349d92eeb 100755 --- a/activerecord/test/base_test.rb +++ b/activerecord/test/base_test.rb @@ -1050,19 +1050,39 @@ class BasicsTest < Test::Unit::TestCase def test_count_with_join res = Post.count_by_sql "SELECT COUNT(*) FROM posts LEFT JOIN comments ON posts.id=comments.post_id WHERE posts.#{QUOTED_TYPE} = 'Post'" - res2 = res + 1 + res2 = nil assert_nothing_raised do res2 = Post.count("posts.#{QUOTED_TYPE} = 'Post'", "LEFT JOIN comments ON posts.id=comments.post_id") end assert_equal res, res2 - res3 = res + 1 + res3 = nil assert_nothing_raised do res3 = Post.count(:conditions => "posts.#{QUOTED_TYPE} = 'Post'", :joins => "LEFT JOIN comments ON posts.id=comments.post_id") end assert_equal res, res3 + + res4 = Post.count_by_sql "SELECT COUNT(p.id) FROM posts p, comments c WHERE p.#{QUOTED_TYPE} = 'Post' AND p.id=c.post_id" + res5 = nil + assert_nothing_raised do + res5 = Post.count(:conditions => "p.#{QUOTED_TYPE} = 'Post' AND p.id=c.post_id", + :joins => "p, comments c", + :select => "p.id") + end + + assert_equal res4, res5 + + res6 = Post.count_by_sql "SELECT COUNT(DISTINCT p.id) FROM posts p, comments c WHERE p.#{QUOTED_TYPE} = 'Post' AND p.id=c.post_id" + res7 = nil + assert_nothing_raised do + res7 = Post.count(:conditions => "p.#{QUOTED_TYPE} = 'Post' AND p.id=c.post_id", + :joins => "p, comments c", + :select => "p.id", + :distinct => true) + end + assert_equal res6, res7 end def test_clear_association_cache_stored |