Skip to content

Commit 768ebf9

Browse files
authored
Merge pull request rails#48385 from adrianna-chang-shopify/ac-autosave-belongs-to-destroy
Fix destroying belongs_to associations for CPK
2 parents acd02a2 + be231a7 commit 768ebf9

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

activerecord/lib/active_record/autosave_association.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -501,7 +501,8 @@ def save_belongs_to_association(reflection)
501501
autosave = reflection.options[:autosave]
502502

503503
if autosave && record.marked_for_destruction?
504-
self[reflection.foreign_key] = nil
504+
foreign_key = Array(reflection.foreign_key)
505+
foreign_key.each { |key| self[key] = nil }
505506
record.destroy
506507
elsif autosave != false
507508
saved = record.save(validate: !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)

activerecord/test/cases/autosave_association_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1028,6 +1028,18 @@ def test_should_destroy_a_parent_association_as_part_of_the_save_transaction_if_
10281028
assert_nil Pirate.find_by_id(id)
10291029
end
10301030

1031+
# belongs_to for CPK
1032+
def test_autosave_cpk_association_should_destroy_parent_association_when_marked_for_destruction
1033+
book = Cpk::Book.new(title: "Book", author_id: 1, number: 2)
1034+
Cpk::Order.create!(id: [3, 4], book: book)
1035+
1036+
book.order.mark_for_destruction
1037+
1038+
assert book.save
1039+
assert_nil book.reload.order
1040+
assert_nil Cpk::Order.find_by(id: 4, shop_id: 3)
1041+
end
1042+
10311043
def test_should_skip_validation_on_a_parent_association_if_marked_for_destruction
10321044
@ship.pirate.catchphrase = ""
10331045
assert_not_predicate @ship, :valid?

activerecord/test/models/cpk/book.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ class Book < ActiveRecord::Base
55
self.table_name = :cpk_books
66
self.primary_key = [:author_id, :number]
77

8+
belongs_to :order, autosave: true, query_constraints: [:shop_id, :order_id]
89
belongs_to :author, class_name: "Cpk::Author"
910
end
1011

0 commit comments

Comments
 (0)