Skip to content

Commit e856d7f

Browse files
committed
[Fixes rails#48080] Fix broken distinct in ActiveRecord::Calculations#ids with includes(...).order(...)
1 parent 912096d commit e856d7f

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

activerecord/lib/active_record/relation/calculations.rb

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -325,19 +325,22 @@ def async_pick(*column_names)
325325
# Person.ids # SELECT people.id FROM people
326326
# Person.joins(:companies).ids # SELECT people.id FROM people INNER JOIN companies ON companies.id = people.company_id
327327
def ids
328+
primary_key_array = Array(primary_key)
329+
328330
if loaded?
329-
result = records.pluck(*Array(primary_key))
331+
result = records.pluck(*primary_key_array)
330332
return @async ? Promise::Complete.new(result) : result
331333
end
332334

333335
if has_include?(primary_key)
334-
relation = apply_join_dependency.distinct
336+
relation = apply_join_dependency.group(*primary_key_array)
335337
return relation.ids
336338
end
337339

338-
columns = arel_columns(Array(primary_key))
340+
columns = arel_columns(primary_key_array)
339341
relation = spawn
340342
relation.select_values = columns
343+
341344
result = if relation.where_clause.contradiction?
342345
ActiveRecord::Result.empty
343346
else

activerecord/test/cases/calculations_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1049,6 +1049,12 @@ def test_ids_with_includes
10491049
assert_equal Company.all.map(&:id).sort, Company.all.includes(:contracts).ids.sort
10501050
end
10511051

1052+
def test_ids_with_includes_and_non_primary_key_order
1053+
rating = 1
1054+
Company.all.each { |company| company.update!(rating: rating += 1) }
1055+
assert_equal Company.all.sort_by(&:rating).map(&:id), Company.includes(:comments).order(:rating).ids
1056+
end
1057+
10521058
def test_ids_with_includes_and_scope
10531059
scoped_ids = [1, 2]
10541060
company = Company.where(id: scoped_ids).first

0 commit comments

Comments
 (0)