Skip to content

Commit

Permalink
Merge pull request rails#9078 from senny/6865_ar_count_with_uniq
Browse files Browse the repository at this point in the history
`#count` in conjunction with `#uniq` performs distinct count.
Conflicts:
	activerecord/CHANGELOG.md
  • Loading branch information
rafaelfranca committed Feb 2, 2013
1 parent 8f8ae5f commit bf794bb
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
9 changes: 9 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,5 +1,14 @@
## Rails 3.2.12 (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*

* Fix `ActiveRecord::Relation#pluck` when columns or tables are reserved words.
Backport #7536.
Fix #8968.
Expand Down
3 changes: 2 additions & 1 deletion activerecord/lib/active_record/relation/calculations.rb
Expand Up @@ -195,7 +195,8 @@ def pluck(column_name)
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)
Expand Down
4 changes: 4 additions & 0 deletions activerecord/test/cases/calculations_test.rb
Expand Up @@ -369,6 +369,10 @@ def test_count_with_column_parameter
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.count(:firm_id, :conditions => "credit_limit = 50 AND firm_id IS NOT NULL")
end
Expand Down

0 comments on commit bf794bb

Please sign in to comment.