Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Unset association when existing record is destroyed.

To avoid foreign key errors (and invalid data) in the database, when a belongs_to association is destroyed, it should also be nil'd out on the parent object.
  • Loading branch information...
commit 217a8b01b1349d50fc9c331e9411034289c640ab 1 parent 5497432
@jcoleman jcoleman authored
View
1  activerecord/lib/active_record/autosave_association.rb
@@ -402,6 +402,7 @@ def save_belongs_to_association(reflection)
autosave = reflection.options[:autosave]
if autosave && record.marked_for_destruction?
+ self[reflection.foreign_key] = nil
record.destroy
elsif autosave != false
saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)
View
16 activerecord/test/cases/nested_attributes_test.rb
@@ -450,6 +450,22 @@ def test_should_destroy_an_existing_record_if_there_is_a_matching_id_and_destroy
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
[nil, '0', 0, 'false', false].each do |not_truth|
@ship.update_attributes(:pirate_attributes => { :id => @ship.pirate.id, :_destroy => not_truth })
Please sign in to comment.
Something went wrong with that request. Please try again.