using fields_for in several places

fields-for, forms, ruby-on-rails

Solution

You can set index manually for each item, but you have to iterate through your items for that to get item index:

  <% ad_form.fields_for :ad_items do |f| %>
     <%= f.text_area "comment", :class => "comment", :rows => "5" %>
  <% end %>
  ...
  <% ad_items.each_with_index do |item, i| %>
    <% ad_form.fields_for :ad_items, item, :child_index => i do |f| %>
      <% render :partial => "detailed_item_settings", :locals => {:f => f} %>
    <% end %>
  <% end %>

Problem

I have a simple model ``` class Ad < ActiveRecord::Base has_many :ad_items end class AdItem < ActiveRecord::Base belongs_to :ad end ``` I have an "ads/new" view, that shows me the form for creating the new ad and adding some items to it The .html.erb code is like a following: ``` <% form_for @ad, do |ad_form| %> <!-- some html --> <% ad_form.fields_for :ad_items do |f| %> <%= f.text_area "comment", :class => "comment", :rows => "5" %> <% end %> <!-- some other html --> <% ad_form.fields_for :ad_items do |f| %> <% render :partial => "detailed_item_settings", :locals => {:f => f} %> <% end %> <% end %> ``` When the ad has one item ... ``` def new @ad = session[:user].ads.build # Create one item for the ad. Another items will be created on the # client side @ad.ad_items.build # standard stuff ... end ``` ... resulting HTML, will look like this: ``` <form ... > <!-- some html --> <textarea id="ad_items_attributes_0_comment" name="ad[ad_items_attributes][0][comment]" /> <!-- some other html --> <!-- "detailed_item_settings" partial's content --> <textarea id="ad_ad_items_attributes_1_desc" name="ad[ad_items_attributes][1][desc]" /> <!-- end --> </form> ``` As it states in the code, i use fields_for method twice, because of the HTML structure, that i must follow For the second "fields_for" call, index for "item" is already 1, not 0, as i expect. It's like, that by calling "fields_for" method, some internal counter will be incremented ... But this is a little strange behaviour ... I've tried to set :index => 0 for fields_for, but all stays the same ... What's wrong here ?

Original source