Skip to content

Commit 2fa7d52

Browse files
authored
Merge pull request rails#51345 from Shopify/allow-association-primary-key-to-be-an-array
Allow `primary_key:` association option to be composite
2 parents e6f92f1 + cc4f368 commit 2fa7d52

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

activerecord/lib/active_record/reflection.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -862,7 +862,11 @@ def association_class
862862
# klass option is necessary to support loading polymorphic associations
863863
def association_primary_key(klass = nil)
864864
if primary_key = options[:primary_key]
865-
@association_primary_key ||= -primary_key.to_s
865+
@association_primary_key ||= if primary_key.is_a?(Array)
866+
primary_key.map { |pk| pk.to_s.freeze }.freeze
867+
else
868+
-primary_key.to_s
869+
end
866870
elsif (klass || self.klass).has_query_constraints? || options[:query_constraints]
867871
(klass || self.klass).composite_query_constraints_list
868872
elsif (klass || self.klass).composite_primary_key?

activerecord/test/cases/associations/belongs_to_associations_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,18 @@ def test_building_the_belonging_object_for_composite_primary_key
371371
assert_equal id, cpk_book.order_id
372372
end
373373

374+
def test_belongs_to_with_explicit_composite_primary_key
375+
cpk_book = cpk_books(:cpk_great_author_first_book)
376+
order = cpk_book.build_order_explicit_fk_pk
377+
order.shop_id = 123
378+
cpk_book.save
379+
380+
shop_id, id = order.id
381+
assert_equal id, cpk_book.order_id
382+
assert_equal shop_id, cpk_book.shop_id
383+
assert_equal order, cpk_book.reload.order_explicit_fk_pk
384+
end
385+
374386
def test_belongs_to_with_inverse_association_for_composite_primary_key
375387
author = Cpk::Author.new(name: "John")
376388
book = author.books.build(id: [nil, 1], title: "The Rails Way")

activerecord/test/models/cpk/book.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ class Book < ActiveRecord::Base
66

77
self.table_name = :cpk_books
88
belongs_to :order, autosave: true, query_constraints: [:shop_id, :order_id], counter_cache: true
9+
belongs_to :order_explicit_fk_pk, class_name: "Cpk::Order", query_constraints: [:shop_id, :order_id], primary_key: [:shop_id, :id]
910
belongs_to :author, class_name: "Cpk::Author"
1011

1112
has_many :chapters, query_constraints: [:author_id, :book_id]

0 commit comments

Comments
 (0)