I’m using Rails 4.2.3. In my view, I make use of the “fields_for” directive. Notice I use it twice (“f.fields_for :my_object_times”) below …
<div class="field">
<%= f.label "Time" %> <span class="required">*</span><br>
<%= select_tag('my_object[hour]', options_for_select((0..99).to_a.map { |i| i.to_s.rjust(2,'0')}), {:prompt => 'Select Hour'} ) %> hrs
<%= select_tag('my_object[minute]', options_for_select((0..60).to_a.map { |i| i.to_s.rjust(2,'0')}), {:prompt => 'Select Minutes'} ) %> min
<%= select_tag('my_object[second]', options_for_select((0..60).to_a.map { |i| i.to_s.rjust(2,'0')}), {:prompt => 'Select Seconds'} ) %> sec
<%= f.fields_for :my_object_times do |mot| %>
<%= mot.hidden_field :time_in_ms %>
<% end %>
</div>
<div class="field">
<%= f.fields_for :address do |addr| %>
<%= addr.label :address %><br>
City: <%= addr.text_field :city %>
<%= select_tag :state, options_for_select(us_states) %>
<%= country_code_select(:country, :country_id,
nil,
{:include_blank=>false},
{:style=>''}
) %>
<% end %>
</div>
<%= f.fields_for :my_object_times do |rt| %>
<div class="field">
<%= rt.label :overall_rank %><br>
<%= rt.text_field :overall_rank %>
</div>
<div class="field">
<%= rt.label :age_group_rank %><br>
<%= rt.text_field :age_group_rank %>
</div>
<div class="field">
<%= rt.label :gender_rank %><br>
<%= rt.text_field :gender_rank %>
</div>
<% end %>
But when my form gets rendered, the array index on the attributes are displayed differently (one is “0” and the other is “1”) …
<input type="hidden" name="my_object[my_object_times_attributes][0][time_in_ms]" id="my_object_my_object_times_attributes_0_time_in_ms" value="252008000">
…
<input type="text" name="my_object[my_object_times_attributes][1][overall_rank]" id="my_object_my_object_times_attributes_1_overall_rank">
How do I modify my view code so that both attributes get rendered with the “0” index? Note I would prefer to leave the order of my elements on my page exactly as they are.
Two solutions come to mind:
1 - Group your hidden_field (since it's not being shown) with your second form_for which will make it a non-issue and be more elegant.
2 - build your my_object_times object in your controller so when you call the fields_for method you can refer that object which should (I haven't tested it) give it the same reference.
If none of the two options are possible, I'd look at the code and see if there's any way you can refactor to make it work.