Skip to content

Commit 0e99d08

Browse files
authored
Merge pull request rails#48363 from gmcgibbon/has_one_autosave_cpk
Fix has_one autosaving for CPK associations
2 parents a84ef12 + 87c2ad0 commit 0e99d08

File tree

3 files changed

+10
-1
lines changed

3 files changed

+10
-1
lines changed

activerecord/lib/active_record/autosave_association.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -453,7 +453,9 @@ def save_has_one_association(reflection)
453453

454454
if (autosave && record.changed_for_autosave?) || _record_changed?(reflection, record, key)
455455
unless reflection.through_reflection
456-
record[reflection.foreign_key] = key
456+
Array(key).zip(Array(reflection.foreign_key)).each do |primary_key, foreign_key_column|
457+
record[foreign_key_column] = primary_key
458+
end
457459
association.set_inverse_instance(record)
458460
end
459461

activerecord/test/cases/autosave_association_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -486,6 +486,12 @@ def test_validation_does_not_validate_non_dirty_association_target
486486
assert_equal true, squeak.mouse.present?
487487
assert_equal true, squeak.valid?
488488
end
489+
490+
test "composite primary key autosave" do
491+
assert_nothing_raised do
492+
Cpk::Order.create!(id: [1, 2], book: Cpk::Book.new(title: "Book", author_id: 3, number: 4))
493+
end
494+
end
489495
end
490496

491497
class TestDefaultAutosaveAssociationOnAHasManyAssociationWithAcceptsNestedAttributes < ActiveRecord::TestCase

activerecord/test/models/cpk/order.rb

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

88
has_many :order_agreements, primary_key: :id
99
has_many :books, query_constraints: [:shop_id, :order_id]
10+
has_one :book, query_constraints: [:shop_id, :order_id]
1011
end
1112

1213
class BrokenOrder < Order

0 commit comments

Comments
 (0)