シンプルなモデルがあります
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 %>
広告に1つのアイテムがある場合...
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メソッドを2回使用します。
2番目の"fields_for"呼び出しでは、 "item"のインデックスはすでに1であり、予想どおり0ではありません。
「fields_for」メソッドを呼び出すことで、内部カウンターがインクリメントされるようなものです...
しかし、これは少し奇妙な動作です...
fields_forに:index => 0を設定しようとしましたが、すべて同じままです...
ここで何が問題になっていますか?