在几个地方使用fields_for

Ant*_*nAL 9 forms ruby-on-rails fields-for

我有一个简单的模型

class Ad < ActiveRecord::Base
   has_many :ad_items
end

class AdItem < ActiveRecord::Base
   belongs_to :ad
end
Run Code Online (Sandbox Code Playgroud)

我有一个"广告/新"视图,向我显示创建新广告并向其添加一些项目的表单

.html.erb代码如下所示:

<% 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 %>
Run Code Online (Sandbox Code Playgroud)

当广告有一个项目时......

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
Run Code Online (Sandbox Code Playgroud)

...结果HTML,将如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

正如它在代码中所述,我使用fields_for方法两次,因为HTML结构,我必须遵循

对于第二个"fields_for"调用,"item"的索引已经是1,而不是0,正如我所期望的那样.

就像,通过调用"fields_for"方法,一些内部计数器将递增...

但这有点奇怪......

我试过设置:index => 0 for fields_for,但都保持不变...

这有什么不对?

Voy*_*yta 18

您可以为每个项目手动设置索引,但是您必须遍历项目以获取项目索引:

  <% 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 %>
Run Code Online (Sandbox Code Playgroud)