views:

363

answers:

1

In regular forms in Ruby on Rails, if using form_for to build a model, as the API docs state, form_for doesn't create an exclusive scope, and it's possible to use form_tag functions within the form_for form.

For example:

<% form_for :person, @person, :url => { :action => "update" } do |f| %>
  First name: <%= f.text_field :first_name %>
  Admin?    : <%= check_box_tag "person[admin]", @person.company.admin? %>
<% end %>

However, in a nested form, the labels and fields have names that are automatically generated by Rails to be associated with a given nested model and not to overlap if multiple nested models are created at once. Is it possible to still use the form_tag functions?

I'd like to do something like this:

<% person_form.fields_for :children do |child_form| %>
Name: <%= child_form.text_field :name %>

Give up for Adoption?: <%= check_box_tag "adoption_" + child_form_index, false %>
<% end %>

However, I don't know how to get access to the child_form's index to ensure that check_box_tag has a unique value if there are multiple children.

Is what I'm trying to do possible?

+1  A: 

See the docs for fields_for under one-to-many.

It looks to me like basically you can just use each (or each_with_index) and pass the block variable along with the symbol:

   <% form_for @person, :url => { :action => "update" } do |person_form| %>
    ...
    <% @person.children.each_with_index do |child, index| %>
        <% person_form.fields_for :children, child do |children_fields| %>
          Name: <%= children_fields.text_field :name %>
         Give up for Adoption?: <%= check_box_tag "adoption_" + index, false %>
        <% end %>
    <% end %>
  <% end %>

Of course, you'll have to handle the "offer for adoption" login on your own.

floyd