【问题标题】:using fields_for in several places在几个地方使用 fields_for
【发布时间】:2010-05-20 12:59:56
【问题描述】:

我有一个简单的模型

class Ad < ActiveRecord::Base
   has_many :ad_items
end

class AdItem < ActiveRecord::Base
   belongs_to :ad
end

我有一个“广告/新”视图,它向我展示了创建新广告并向其添加一些项目的表单

.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 %>

当广告只有一项时...

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

...生成的 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>

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

对于第二个“fields_for”调用,“item”的索引已经是 1,而不是我期望的 0。

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

但这是一个有点奇怪的行为......

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

这里有什么问题?

【问题讨论】:

    标签: ruby-on-rails forms fields-for


    【解决方案1】:

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

      <% 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 %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-12
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多