Skip to content

Commit

Permalink
Merge pull request rails#52744 from fatkodima/count-with-multiple-are…
Browse files Browse the repository at this point in the history
…l-selects

Fix `distinct.count` when using `select` with multiple arel expressions
  • Loading branch information
kamipo authored Sep 2, 2024
2 parents 1cb63d0 + 6be1ce4 commit 6484a3c
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 6484a3c

Please sign in to comment.