Skip to content

Commit 12fc98f

Browse files
authored
Merge pull request rails#47924 from Shopify/fix-autosave-for-models-assoc-with-a-cpk-model
Fix replacing foreign key for a CPK association by id attribute
2 parents 3d4dd9f + c0da60f commit 12fc98f

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

activerecord/lib/active_record/autosave_association.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -505,12 +505,12 @@ def save_belongs_to_association(reflection)
505505
saved = record.save(validate: !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)
506506

507507
if association.updated?
508-
primary_key = Array(compute_primary_key(reflection, record))
508+
primary_key = Array(compute_primary_key(reflection, record)).map(&:to_s)
509509
foreign_key = Array(reflection.foreign_key)
510510

511511
primary_key_foreign_key_pairs = primary_key.zip(foreign_key)
512512
primary_key_foreign_key_pairs.each do |primary_key, foreign_key|
513-
association_id = record.public_send(primary_key)
513+
association_id = record._read_attribute(primary_key)
514514
self[foreign_key] = association_id unless self[foreign_key] == association_id
515515
end
516516
association.loaded!
@@ -527,7 +527,7 @@ def compute_primary_key(reflection, record)
527527
elsif reflection.options[:query_constraints] && (query_constraints = record.class.query_constraints_list)
528528
query_constraints
529529
else
530-
:id
530+
record.class.primary_key
531531
end
532532
end
533533

activerecord/test/cases/associations_test.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,22 @@ def test_assign_composite_foreign_key_belongs_to_association
287287
assert_equal(another_blog.id, comment.blog_id)
288288
end
289289

290+
291+
def test_assign_belongs_to_cpk_model_by_id_attribute
292+
order = cpk_orders(:cpk_groceries_order_1)
293+
agreement = Cpk::OrderAgreement.new(signature: "signed")
294+
295+
agreement.order = order
296+
agreement.save
297+
298+
assert_not_nil(agreement.reload.order)
299+
assert_not_nil(agreement.order_id)
300+
301+
assert_equal(order, agreement.order)
302+
_shop_id, order_id = order.id
303+
assert_equal(order_id, agreement.order_id)
304+
end
305+
290306
def test_append_composite_foreign_key_has_many_association_with_autosave
291307
blog_post = sharded_blog_posts(:great_post_blog_one)
292308
comment = Sharded::Comment.new(body: "Great post! :clap:")

0 commit comments

Comments
 (0)