Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix destroying belongs_to associations for CPK #48385

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion activerecord/lib/active_record/autosave_association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,8 @@ def save_belongs_to_association(reflection)
autosave = reflection.options[:autosave]

if autosave && record.marked_for_destruction?
self[reflection.foreign_key] = nil
foreign_key = Array(reflection.foreign_key)
foreign_key.each { |key| self[key] = nil }
record.destroy
elsif autosave != false
saved = record.save(validate: !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)
Expand Down
12 changes: 12 additions & 0 deletions activerecord/test/cases/autosave_association_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1028,6 +1028,18 @@ def test_should_destroy_a_parent_association_as_part_of_the_save_transaction_if_
assert_nil Pirate.find_by_id(id)
end

# belongs_to for CPK
def test_autosave_cpk_association_should_destroy_parent_association_when_marked_for_destruction
book = Cpk::Book.new(title: "Book", author_id: 1, number: 2)
Cpk::Order.create!(id: [3, 4], book: book)

book.order.mark_for_destruction

assert book.save
assert_nil book.reload.order
assert_nil Cpk::Order.find_by(id: 4, shop_id: 3)
end

def test_should_skip_validation_on_a_parent_association_if_marked_for_destruction
@ship.pirate.catchphrase = ""
assert_not_predicate @ship, :valid?
Expand Down
1 change: 1 addition & 0 deletions activerecord/test/models/cpk/book.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ class Book < ActiveRecord::Base
self.table_name = :cpk_books
self.primary_key = [:author_id, :number]

belongs_to :order, autosave: true, query_constraints: [:shop_id, :order_id]
gmcgibbon marked this conversation as resolved.
Show resolved Hide resolved
belongs_to :author, class_name: "Cpk::Author"
end

Expand Down