Topic: Forms with Polymorphic Association and acts_as_tree

I am unsure of how to get data from a child row in my acts_as_tree hierarchy into a form element using a modeled form helper, as opposed to a non-model (text_field_tag). I have two models:

ContentEntry and Page

Schema for ContentEntry:

  create_table "content_entries", :force => true do |t|
    t.column "parent_id",     :integer
    t.column "name",          :string
    t.column "resource_id",   :integer
    t.column "resource_type", :string
  end

Schema for Page:
  create_table "pages", :force => true do |t|
    t.column "content",     :text
    t.column "created_at",  :datetime
    t.column "updated_at",  :datetime
    t.column "template_id", :integer
    t.column "version",     :integer
  end

ContentEntry model:
class ContentEntry < ActiveRecord::Base
  acts_as_tree
  belongs_to :resource, :polymorphic => true
  validates_presence_of :name
end

Page model:
class Page < ActiveRecord::Base
  acts_as_versioned

  has_one :content_entry, :as => :resource, :dependent => true
  belongs_to :template

  validates_presence_of :content
end


Now my problem is when I try to access a child ContentEntry with a form. I'm able to pull the data with a non-model form helper:

edit.rhtml

<%= render :partial => 'part', :collection => @content_entry.children %>

_part.rhtml
<%= text_field_tag 'part', part.name %></p>

However, I want to use a model form helper, like:
<%= text_field 'content_entry', 'name' %>

If this is possible, how do I do it along with manipulating the data in my controller? Hopefully this makes sense.

Last edited by wesr (2006-12-21 15:40:50)

Re: Forms with Polymorphic Association and acts_as_tree

You can find an excellent explanation of how to do this right here:
http://railsforum.com/viewtopic.php?pid=3714

Our very own RyanB wrote a great (and simple!) introduction to creating a form to edit many models.

Re: Forms with Polymorphic Association and acts_as_tree

Thanks danger for pointing me in that direction.

Here is my solution:

<% for @child in @content_entry.children %>
    <% fields_for "child[]" do |f| %>
        <p><label>Part name:</label><br />
            <%= f.text_field :name %></p>
        <% @part = @child.resource %>
        <% fields_for "part[]" do |f| %>
            <p><label>Part body:</label><br />
                <%= f.text_area :content, :cols => 74, :rows => 20 %></p>
        <% end %>
    <% end %>
<% end %>