Only call set_owner_attributes for has_one association if target exists.

This commit is contained in:
Dieter Komendera 2011-07-04 18:39:25 +02:00
parent 718542bb18
commit 7d3aa2462c
2 changed files with 12 additions and 1 deletions

View File

@ -19,7 +19,7 @@ module ActiveRecord
if owner.persisted? && save && !record.save
nullify_owner_attributes(record)
set_owner_attributes(target)
set_owner_attributes(target) if target
raise RecordNotSaved, "Failed to save the new associated #{reflection.name}."
end
end

View File

@ -345,6 +345,17 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert orig_ship.destroyed?
end
def test_creation_failure_due_to_new_record_should_raise_error
pirate = pirates(:redbeard)
new_ship = Ship.new
assert_raise(ActiveRecord::RecordNotSaved) do
pirate.ship = new_ship
end
assert_nil pirate.ship
assert_nil new_ship.pirate_id
end
def test_replacement_failure_due_to_existing_record_should_raise_error
pirate = pirates(:blackbeard)
pirate.ship.name = nil