Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #5248 from jcoleman/should-unset-association-when-…

…an-existing-record-is-destroyed

Unset association when existing record is destroyed.
  • Loading branch information...
commit 834d6da54e459f6354fe7b349779d690652cc7a8 2 parents a507c64 + 217a8b0
@jonleighton jonleighton authored
View
1  activerecord/lib/active_record/autosave_association.rb
@@ -394,6 +394,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
@@ -463,6 +463,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])
@skojin
skojin added a note

why sql for so simple check? better where(id: original_pirate_id])

or assert !Pirate.where(id: original_pirate_id]).exists?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ 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 })
@skojin

why sql for so simple check? better where(id: original_pirate_id])

or assert !Pirate.where(id: original_pirate_id]).exists?

Please sign in to comment.
Something went wrong with that request. Please try again.