Raise an exception with friendlier error message when attempting to build a polymorphic belongs_to with accepts_nested_attributes_for. [#2318 state:resolved]

Signed-off-by: Eloy Duran <eloy.de.enige@gmail.com>
This commit is contained in:
Mike Breen 2009-07-11 14:30:35 +02:00 committed by Eloy Duran
parent 3180619c0d
commit bcd0ef710e
3 changed files with 16 additions and 1 deletions

@ -260,7 +260,12 @@ def assign_nested_attributes_for_one_to_one_association(association_name, attrib
if attributes['id'].blank? if attributes['id'].blank?
unless reject_new_record?(association_name, attributes) unless reject_new_record?(association_name, attributes)
send("build_#{association_name}", attributes.except(*UNASSIGNABLE_KEYS)) method = "build_#{association_name}"
if respond_to?(method)
send(method, attributes.except(*UNASSIGNABLE_KEYS))
else
raise ArgumentError, "Cannot build association #{association_name}. Are you trying to build a polymorphic one-to-one association?"
end
end end
elsif (existing_record = send(association_name)) && existing_record.id.to_s == attributes['id'].to_s elsif (existing_record = send(association_name)) && existing_record.id.to_s == attributes['id'].to_s
assign_to_or_mark_for_destruction(existing_record, attributes, allow_destroy) assign_to_or_mark_for_destruction(existing_record, attributes, allow_destroy)

@ -81,11 +81,19 @@ def test_a_model_should_respond_to_underscore_delete_and_return_if_it_is_marked_
end end
class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
include AssertRaiseWithMessage
def setup def setup
@pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?") @pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@ship = @pirate.create_ship(:name => 'Nights Dirty Lightning') @ship = @pirate.create_ship(:name => 'Nights Dirty Lightning')
end end
def test_should_raise_argument_error_if_trying_to_build_polymorphic_belongs_to
assert_raise_with_message ArgumentError, "Cannot build association looter. Are you trying to build a polymorphic one-to-one association?" do
Treasure.new(:name => 'pearl', :looter_attributes => {:catchphrase => "Arrr"})
end
end
def test_should_define_an_attribute_writer_method_for_the_association def test_should_define_an_attribute_writer_method_for_the_association
assert_respond_to @pirate, :ship_attributes= assert_respond_to @pirate, :ship_attributes=
end end

@ -3,4 +3,6 @@ class Treasure < ActiveRecord::Base
belongs_to :looter, :polymorphic => true belongs_to :looter, :polymorphic => true
has_many :price_estimates, :as => :estimate_of has_many :price_estimates, :as => :estimate_of
accepts_nested_attributes_for :looter
end end