Rails accepts_nested_attributes_for and build_attribute with polymorphic relationships

Posted by SooDesuNe on Stack Overflow See other posts from Stack Overflow or by SooDesuNe
Published on 2010-06-15T00:21:49Z Indexed on 2010/06/15 0:22 UTC
Read the original article Hit count: 517

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about relationship