Skip to content

Commit cc4f368

Browse files
committed
Allow primary_key: association option to be composite
Association's `primary_key` can be composite when derived from associated class `primary_key` or `query_constraints`. But we don't allow setting it explicitly even though Rails is already capable of supporting it. This commit allows `primary_key` association option to be an array.
1 parent 83a0132 commit cc4f368

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
@@ -870,7 +870,11 @@ def association_class
870870
# klass option is necessary to support loading polymorphic associations
871871
def association_primary_key(klass = nil)
872872
if primary_key = options[:primary_key]
873-
@association_primary_key ||= -primary_key.to_s
873+
@association_primary_key ||= if primary_key.is_a?(Array)
874+
primary_key.map { |pk| pk.to_s.freeze }.freeze
875+
else
876+
-primary_key.to_s
877+
end
874878
elsif (klass || self.klass).has_query_constraints? || options[:query_constraints]
875879
(klass || self.klass).composite_query_constraints_list
876880
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)