Permalink
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...
1 parent 5497432 commit 217a8b01b1349d50fc9c331e9411034289c640ab @jcoleman jcoleman committed Mar 2, 2012
@@ -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?)
@@ -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 })

0 comments on commit 217a8b0

Please sign in to comment.