开发者

Rails 3.1 - :fields_for, :child_index not incrementing

开发者 https://www.devze.com 2023-04-11 01:40 出处:网络
I have a nested attributes form with the following and am just learning how to use nested attributes. One problem I\'m having is that the child_index values is not incrementing up. I\'m getting3 field

I have a nested attributes form with the following and am just learning how to use nested attributes. One problem I'm having is that the child_index values is not incrementing up. I'm getting 3 fields based upon the build in the controller but they all have 0 or 1 depending on what number is set to.

Any ideas on how to get this to increment?

# in controller: 3.times {@item.assets.build}
<% number = 1 %>
<div id='files'>
  <%= f.fields_for :assets, :child_index => number do |asset| %>
    <p>
    number:<%= number %><br />
    <%=asset.label :asset, "File ##{number += 1}" %>
    <%= asset.file_field :asset %>
   </p>
<% end 开发者_高级运维%>
</div>
<%= f.submit %>

edit: so all of them in html would have the form like:

item[assets_attributes][0][asset]

rather than the desired:

menu_item[assets_attributes][0][asset]
menu_item[assets_attributes][1][asset] 
menu_item[assets_attributes][2][asset]

edit #2: so looking through the source code, I see the following and am wondering if rails is supposed to be doing some auto-swapping and possibly this isn't happening;

<input id="item_assets_attributes_0_asset" name="item[assets_attributes][0][asset]" type="file" />
<input id="item_assets_attributes_0_id" name="item[assets_attributes][0][id]" type="hidden" value="1" />


Looking through the Rails source it's clear that if you specify :child_index there will be no auto-increment. Whether or not that is the proper behavior is debatable. If you completely omit the :child_index when calling fields_for, you should get the indexes you desire.

To get the correct label for each field you could use some JavaScript. If you don't like that, you could set the file number as an attribute of the Asset class.

class Asset < AR
  attr_accessor :file_number
end

# in controller: 3.times {|n| @item.assets.build(:file_number => n) }

<div id='files'>
  <%= f.fields_for :assets do |asset| %>
    <p>
    <%=asset.label :asset, "File ##{asset.file_number}" %>
    <%= asset.file_field :asset %>
   </p>
<% end %>
</div>
<%= f.submit %>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号