Skip to content

Commit

Permalink
Fix distinct.count when using select with multiple arel expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima committed Aug 29, 2024
1 parent c692e75 commit 6be1ce4
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
8 changes: 6 additions & 2 deletions activerecord/lib/active_record/relation/calculations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -635,8 +635,12 @@ def select_for_count

adapter_class = model.adapter_class
select_values.map do |field|
column = arel_column(field.to_s) do |attr_name|
Arel.sql(attr_name)
column = if Arel.arel_node?(field)
field
else
arel_column(field.to_s) do |attr_name|
Arel.sql(attr_name)
end
end

if column.is_a?(Arel::Nodes::SqlLiteral)
Expand Down
7 changes: 7 additions & 0 deletions activerecord/test/cases/calculations_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -623,6 +623,13 @@ def test_count_selected_arel_attribute
assert_equal 4, Account.distinct.select(Account.arel_table[:firm_id]).count
end

def test_count_selected_arel_attributes
# Only MySQL supports COUNT with multiple columns, and only with DISTINCT.
skip unless current_adapter?(:Mysql2Adapter, :TrilogyAdapter)

assert_equal 5, Account.distinct.select(Account.arel_table[:id], Account.arel_table[:firm_id]).count
end

def test_count_with_column_parameter
assert_equal 5, Account.count(:firm_id)
end
Expand Down

0 comments on commit 6be1ce4

Please sign in to comment.