Rails 3.1 -: fields_for ,: child_index not increasing

I have a nested attribute form with the following and I'm just learning how to use nested attributes. One of the problems I am facing is that the values โ€‹โ€‹of child_index are not incremented. I get 3 fields based on the assembly in the controller, but they all have 0 or 1 depending on what number is set to.

Any ideas on how to make this increase?

# 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 will have the form:

 item[assets_attributes][0][asset] 

not desired:

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

edit # 2: therefore, looking at the source code, I see the following and wonder if the rails should do automatic pumping and maybe this does not happen;

 <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" /> 
+4
source share
1 answer

Looking through the source of Rails, it is clear that if you specify :child_index , there will be no automatic increase. Regardless of whether this is the correct behavior is controversial. If you completely omit :child_index when calling fields_for , you should get the indices you need.

To get the correct label for each field, you can use some JavaScript. If you do not like this, you can 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 %> 
+3
source

All Articles