Rails accepts_nested_attributes_for and build_attribute with polymorphic relationships
- by SooDesuNe
The core of this question is where build_attribute is required in a model with nested attribuites
I'm working with a few models that are setup like:
class Person < ActiveRecord::Base
has_one :contact
accepts_nested_attributes_for :contact, :allow_destroy=> true
end
class Contact < ActiveRecord::Base
belongs_to :person
has_one :address, :as=>:addressable
accepts_nested_attributes_for :address, :allow_destroy=> true
end
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic=>true
end
I have to define the new method of people_controller like:
def new
@person = Person.new
@person.build_contact
@person.contact.build_address #!not very good encapsulation
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @person }
end
end
Without @person.contact.build_address the address relationship on contact is NIL. I don't like having to build_address in people_controller. That should be handled by Contact. Where do I define this in Contact since the contacts_controller is not involved here?