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

Unset association when existing record is destroyed. #5248

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
1 change: 1 addition & 0 deletions activerecord/lib/active_record/autosave_association.rb
Expand Up @@ -402,6 +402,7 @@ def save_belongs_to_association(reflection)
autosave = reflection.options[:autosave] autosave = reflection.options[:autosave]


if autosave && record.marked_for_destruction? if autosave && record.marked_for_destruction?
self[reflection.foreign_key] = nil
record.destroy record.destroy
elsif autosave != false elsif autosave != false
saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?) saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)
Expand Down
16 changes: 16 additions & 0 deletions activerecord/test/cases/nested_attributes_test.rb
Expand Up @@ -450,6 +450,22 @@ def test_should_destroy_an_existing_record_if_there_is_a_matching_id_and_destroy
end end
end end


def test_should_unset_association_when_an_existing_record_is_destroyed
@ship.reload
original_pirate_id = @ship.pirate.id
@ship.attributes = {:pirate_attributes => {:id => @ship.pirate.id, :_destroy => true}}
@ship.save!

assert_empty Pirate.where(["id = ?", original_pirate_id])
assert_nil @ship.pirate_id
assert_nil @ship.pirate

@ship.reload
assert_empty Pirate.where(["id = ?", original_pirate_id])
assert_nil @ship.pirate_id
assert_nil @ship.pirate
end

def test_should_not_destroy_an_existing_record_if_destroy_is_not_truthy def test_should_not_destroy_an_existing_record_if_destroy_is_not_truthy
[nil, '0', 0, 'false', false].each do |not_truth| [nil, '0', 0, 'false', false].each do |not_truth|
@ship.update_attributes(:pirate_attributes => { :id => @ship.pirate.id, :_destroy => not_truth }) @ship.update_attributes(:pirate_attributes => { :id => @ship.pirate.id, :_destroy => not_truth })
Expand Down