Skip to content

Commit 995768e

Browse files
authored
Merge pull request rails#47762 from Shopify/ar-calculations-ids-for-a-cpk-model
Fix `ActiveRecord::Calculations#ids` for a composite primary key model
2 parents 643b5a6 + 1217127 commit 995768e

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

activerecord/lib/active_record/relation/calculations.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,7 @@ def async_pick(*column_names)
310310
# Person.joins(:companies).ids # SELECT people.id FROM people INNER JOIN companies ON companies.person_id = people.id
311311
def ids
312312
if loaded?
313-
result = records.pluck(primary_key)
313+
result = records.pluck(*Array(primary_key))
314314
return @async ? Promise::Complete.new(result) : result
315315
end
316316

@@ -319,7 +319,7 @@ def ids
319319
return relation.ids
320320
end
321321

322-
columns = arel_columns([primary_key])
322+
columns = arel_columns(Array(primary_key))
323323
relation = spawn
324324
relation.select_values = columns
325325
result = if relation.where_clause.contradiction?

activerecord/test/cases/calculations_test.rb

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,12 @@
2424
require "models/too_long_table_name"
2525
require "support/stubs/strong_parameters"
2626
require "support/async_helper"
27+
require "models/cpk/book"
2728

2829
class CalculationsTest < ActiveRecord::TestCase
2930
include AsyncHelper
3031

31-
fixtures :companies, :accounts, :authors, :author_addresses, :topics, :speedometers, :minivans, :books, :posts, :comments
32+
fixtures :companies, :accounts, :authors, :author_addresses, :topics, :speedometers, :minivans, :books, :posts, :comments, :cpk_books
3233

3334
def test_should_sum_field
3435
assert_equal 318, Account.sum(:credit_limit)
@@ -940,6 +941,25 @@ def test_ids
940941
assert_equal Company.all.map(&:id).sort, Company.all.ids.sort
941942
end
942943

944+
def ids_for_a_composite_primary_key
945+
assert_equal Cpk::Book.all.map(&:id).sort, Cpk::Book.all.ids.sort
946+
end
947+
948+
def test_ids_for_a_composite_primary_key_with_scope
949+
book = cpk_books(:cpk_great_author_first_book)
950+
951+
assert_equal [[book.author_id, book.number]], Cpk::Book.all.where(title: book.title).ids
952+
end
953+
954+
def test_ids_for_a_composite_primary_key_on_loaded_relation
955+
book = cpk_books(:cpk_great_author_first_book)
956+
relation = Cpk::Book.where(title: book.title)
957+
relation.to_a
958+
959+
assert_predicate relation, :loaded?
960+
assert_equal [[book.author_id, book.number]], relation.ids
961+
end
962+
943963
def test_ids_with_scope
944964
scoped_ids = [1, 2]
945965
assert_equal Company.where(id: scoped_ids).map(&:id).sort, Company.where(id: scoped_ids).ids.sort

0 commit comments

Comments
 (0)