aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJon Leighton <j@jonathanleighton.com>2012-09-21 02:40:26 -0700
committerJon Leighton <j@jonathanleighton.com>2012-09-21 02:40:26 -0700
commit834d6da54e459f6354fe7b349779d690652cc7a8 (patch)
tree690685d9871c69e74ba4669ac57cd0060bc2fc11
parenta507c641ec78ab8781b18c42a75ccad75362af8e (diff)
parent217a8b01b1349d50fc9c331e9411034289c640ab (diff)
downloadrails-834d6da54e459f6354fe7b349779d690652cc7a8.tar.gz
rails-834d6da54e459f6354fe7b349779d690652cc7a8.tar.bz2
rails-834d6da54e459f6354fe7b349779d690652cc7a8.zip
Merge pull request #5248 from jcoleman/should-unset-association-when-an-existing-record-is-destroyed
Unset association when existing record is destroyed.
-rw-r--r--activerecord/lib/active_record/autosave_association.rb1
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb16
2 files changed, 17 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
index 290f57659d..a30f888a7a 100644
--- a/activerecord/lib/active_record/autosave_association.rb
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -394,6 +394,7 @@ module ActiveRecord
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?)
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index 07862ca4ca..9120083eca 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -463,6 +463,22 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase
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 })