# 2 levels nested form with a polymorphic association

**URL:** <https://www.ruby-forum.com/t/2-levels-nested-form-with-a-polymorphic-association/195701>\
**Category:** Rails\
**Created:** [September 28, 2010, 1:15pm UTC](https://www.ruby-forum.com/t/2-levels-nested-form-with-a-polymorphic-association/195701 "2010-09-28T13:15:52Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![temesta](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/e9bcb4/32.png) [@temesta](https://www.ruby-forum.com/u/temesta)\
**Post date:** [September 28, 2010, 1:15pm UTC](https://www.ruby-forum.com/t/2-levels-nested-form-with-a-polymorphic-association/195701/1 "2010-09-28T13:15:52Z")

</div>

Hi,

I’m trying to build a complex nested form for the model ‘page’, which  
has a polymorphic association with different component types.  
Unfortunately it does not seem to work properly.

model “Page” :

has\_many :components, :dependent =\> :destroy  
has\_many :textcomponents, :through =\> :components, :source =\>  
:componentobject , :source\_type =\> “Textcomponent”  
has\_many :componentobjects,:through =\>:components  
accepts\_nested\_attributes\_for :components, :allow\_destroy =\> true ,  
:reject\_if=\>:all\_blank

the polymorphic middle model “Component” :

belongs\_to :componentobject, :polymorphic =\> true  
belongs\_to :page  
accepts\_nested\_attributes\_for :componentobject

a specific component model on the other end ‘Textcomponent’ :

has\_one :component, :as =\> :componentobject  
has\_one :page, :through =\> :component

In the ‘form’ partial of the page controller, I have this code:

\<%= form\_for(@page) do |f| %\>  
\<% f.fields\_for :components do |cmp\_form| %\>  
\<%= cmp\_form.label :cid %\>  
\<%= cmp\_form.text\_field :cid %\>

\<% cmp\_form.fields\_for :componentobject do |cmpo\_form| %\>  
\<% if cmpo\_form.object.class == Textcomponent %\>  
\<%= cmpo\_form.label :value\_nl %\>  
\<%= cmpo\_form.text\_field :value\_nl %\>  
\<% end %\>  
\<% end %\>  
\<% end %\>  
\<% end %\>

And of course in the “Pages” controller I create the nested objects :

def new  
@page = Page.new  
@c = @page.components.build  
@c.componentobject = Textcomponent.new

```
respond_to do |format|
  format.html # new.html.erb
  format.xml { render :xml => @page }
end

```

end

In this case I assume that my ‘cmpo\_form’ part of the form should render  
one instance of the the “Textcomponent”. Unfortunately it doesn’t… I  
looks  
like rails is not finding any textcomponents in the component instance  
of the page.

I’m not sure if I’m missing something, or it just isn’t possible or good  
practice.

Any suggestions would be welcome.
