Skip to content

Commit 6be1ce4

Browse files
committed
Fix distinct.count when using select with multiple arel expressions
1 parent c692e75 commit 6be1ce4

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

activerecord/lib/active_record/relation/calculations.rb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -635,8 +635,12 @@ def select_for_count
635635

636636
adapter_class = model.adapter_class
637637
select_values.map do |field|
638-
column = arel_column(field.to_s) do |attr_name|
639-
Arel.sql(attr_name)
638+
column = if Arel.arel_node?(field)
639+
field
640+
else
641+
arel_column(field.to_s) do |attr_name|
642+
Arel.sql(attr_name)
643+
end
640644
end
641645

642646
if column.is_a?(Arel::Nodes::SqlLiteral)

activerecord/test/cases/calculations_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -623,6 +623,13 @@ def test_count_selected_arel_attribute
623623
assert_equal 4, Account.distinct.select(Account.arel_table[:firm_id]).count
624624
end
625625

626+
def test_count_selected_arel_attributes
627+
# Only MySQL supports COUNT with multiple columns, and only with DISTINCT.
628+
skip unless current_adapter?(:Mysql2Adapter, :TrilogyAdapter)
629+
630+
assert_equal 5, Account.distinct.select(Account.arel_table[:id], Account.arel_table[:firm_id]).count
631+
end
632+
626633
def test_count_with_column_parameter
627634
assert_equal 5, Account.count(:firm_id)
628635
end

0 commit comments

Comments
 (0)