diff options
author | Rafael Mendonça França <rafaelmfranca@gmail.com> | 2013-01-26 03:18:21 -0800 |
---|---|---|
committer | Rafael Mendonça França <rafaelmfranca@gmail.com> | 2013-01-26 03:18:21 -0800 |
commit | 647d18c92c77b96754c7e9e3d9142f18e0772061 (patch) | |
tree | 5655e91d3cf2953515cc2d3c212bbc861c66953d | |
parent | 9df25844ba77f5ebdfe6178c78c63de53c15c45c (diff) | |
parent | 648def406023b38310287588eb5efdfc739253e2 (diff) | |
download | rails-647d18c92c77b96754c7e9e3d9142f18e0772061.tar.gz rails-647d18c92c77b96754c7e9e3d9142f18e0772061.tar.bz2 rails-647d18c92c77b96754c7e9e3d9142f18e0772061.zip |
Merge pull request #9078 from senny/6865_ar_count_with_uniq
`#count` in conjunction with `#uniq` performs distinct count.
-rw-r--r-- | activerecord/CHANGELOG.md | 9 | ||||
-rw-r--r-- | activerecord/lib/active_record/relation/calculations.rb | 3 | ||||
-rw-r--r-- | activerecord/test/cases/calculations_test.rb | 4 |
3 files changed, 15 insertions, 1 deletions
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 278baee68f..6f3bd50f9a 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,5 +1,14 @@ ## Rails 4.0.0 (unreleased) ## +* When `#count` is used in conjunction with `#uniq` we perform `count(:distinct => true)`. + Fix #6865. + + Example: + + relation.uniq.count # => SELECT COUNT(DISTINCT *) + + *Yves Senn + Kaspar Schiess* + * PostgreSQL ranges type support. Includes: int4range, int8range, numrange, tsrange, tstzrange, daterange diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index 3f154bd1cc..f10c290755 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -192,7 +192,8 @@ module ActiveRecord def perform_calculation(operation, column_name, options = {}) operation = operation.to_s.downcase - distinct = options[:distinct] + # If #count is used in conjuction with #uniq it is considered distinct. (eg. relation.uniq.count) + distinct = options[:distinct] || self.uniq_value if operation == "count" column_name ||= (select_for_count || :all) diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index b7622705bf..be49e948fc 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -341,6 +341,10 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal 5, Account.count(:firm_id) end + def test_count_with_uniq + assert_equal 4, Account.select(:credit_limit).uniq.count + end + def test_count_with_column_and_options_parameter assert_equal 2, Account.where("credit_limit = 50 AND firm_id IS NOT NULL").count(:firm_id) end |