"5" %> "detailed_item_sett-6ren">
gpt4 book ai didi

ruby-on-rails - 在几个地方使用fields_for

转载 作者:行者123 更新时间:2023-12-03 11:10:06 24 4
gpt4 key购买 nike

我有一个简单的模型

class Ad < ActiveRecord::Base
has_many :ad_items
end

class AdItem < ActiveRecord::Base
belongs_to :ad
end

我有一个“广告/新” View ,该 View 向我显示了创建新广告并向其中添加一些项目的表单

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

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

对于第二个“fields_for”调用,“项目”的索引已经是1,而不是0,正如我期望的那样。

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

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

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

怎么了

最佳答案

您可以为每个商品手动设置索引,但是您必须遍历商品才能获得商品索引:

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

关于ruby-on-rails - 在几个地方使用fields_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2873889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com