Permalink
Browse files

Ensure the parent record is always saved when the child is invalid. [#…

…2249 state:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information...
1 parent 542d6a0 commit a70c78177a564c2f2cd09846a5e7ab6e8669e9f2 @alloy alloy committed with lifo Mar 17, 2009
@@ -311,11 +311,13 @@ def save_collection_association(reflection)
# ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
def save_has_one_association(reflection)
if (association = association_instance_get(reflection.name)) && !association.target.nil?
- if reflection.options[:autosave] && association.marked_for_destruction?
+ autosave = reflection.options[:autosave]
+
+ if autosave && association.marked_for_destruction?
association.destroy
- elsif new_record? || association.new_record? || association[reflection.primary_key_name] != id || reflection.options[:autosave]
+ elsif new_record? || association.new_record? || association[reflection.primary_key_name] != id || autosave
association[reflection.primary_key_name] = id
- association.save(false)
+ association.save(!autosave)
end
end
end
@@ -330,10 +332,12 @@ def save_has_one_association(reflection)
# ActiveRecord::Base after the AutosaveAssociation module, which it does by default.
def save_belongs_to_association(reflection)
if association = association_instance_get(reflection.name)
- if reflection.options[:autosave] && association.marked_for_destruction?
+ autosave = reflection.options[:autosave]
+
+ if autosave && association.marked_for_destruction?
association.destroy
else
- association.save(false) if association.new_record? || reflection.options[:autosave]
+ association.save(!autosave) if association.new_record? || autosave
if association.updated?
self[reflection.primary_key_name] = association.id
@@ -38,6 +38,17 @@ def base
end
class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
+ def test_should_save_parent_but_not_invalid_child
+ firm = Firm.new(:name => 'GlobalMegaCorp')
+ assert firm.valid?
+
+ firm.build_account_using_primary_key
+ assert !firm.build_account_using_primary_key.valid?
+
+ assert firm.save
+ assert firm.account_using_primary_key.new_record?
+ end
+
def test_save_fails_for_invalid_has_one
firm = Firm.find(:first)
assert firm.valid?
@@ -126,6 +137,17 @@ def test_not_resaved_when_unchanged
end
class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
+ def test_should_save_parent_but_not_invalid_child
+ client = Client.new(:name => 'Joe (the Plumber)')
+ assert client.valid?
+
+ client.build_firm
+ assert !client.firm.valid?
+
+ assert client.save
+ assert client.firm.new_record?
+ end
+
def test_save_fails_for_invalid_belongs_to
assert log = AuditLog.create(:developer_id => 0, :message => "")

0 comments on commit a70c781

Please sign in to comment.