Skip to content
Browse files

Don't double include DISTINCT when the user has already specified it.…

… Closes #11502 [kenneth.kalmer]

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@9223 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
1 parent 295587f commit 50538fb524950798cd8896f693909bdbc620bd8e @NZKoz NZKoz committed Apr 4, 2008
Showing with 8 additions and 1 deletion.
  1. +4 −1 activerecord/lib/active_record/calculations.rb
  2. +4 −0 activerecord/test/cases/calculations_test.rb
View
5 activerecord/lib/active_record/calculations.rb
@@ -169,7 +169,10 @@ def construct_calculation_sql(operation, column_name, options) #:nodoc:
end
end
- sql = "SELECT #{operation}(#{'DISTINCT ' if options[:distinct]}#{column_name}) AS #{aggregate_alias}"
+ if options[:distinct] && column_name.to_s !~ /\s*DISTINCT\s+/i
+ distinct = 'DISTINCT '
+ end
+ sql = "SELECT #{operation}(#{distinct}#{column_name}) AS #{aggregate_alias}"
# A (slower) workaround if we're using a backend, like sqlite, that doesn't support COUNT DISTINCT.
sql = "SELECT COUNT(*) AS #{aggregate_alias}" if use_workaround
View
4 activerecord/test/cases/calculations_test.rb
@@ -241,6 +241,10 @@ def test_should_count_selected_field_with_include
assert_equal 4, Account.count(:distinct => true, :include => :firm, :select => :credit_limit)
end
+ def test_should_count_manual_select_with_include
+ assert_equal 6, Account.count(:select => "DISTINCT accounts.id", :include => :firm)
+ end
+
def test_count_with_column_parameter
assert_equal 5, Account.count(:firm_id)
end

0 comments on commit 50538fb

Please sign in to comment.
Something went wrong with that request. Please try again.