ncri / nested_form_fields

Dynamically add and remove nested has_many association fields in a Ruby on Rails form

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use nested_fields with auto increment number

imrasp opened this issue · comments

commented

I would like to use nested_fields with auto increment number in a hidden field
currently, my code is

<%= f.nested_fields_for(:gate_directions) do |p| %>
  <div class="row" style="margin-top:15px;">
    <div class="col-sm-4">
      <%= p.text_field :name, class: "form-control" %>
    </div>
    <div class="col-sm-3">
      <%= p.hidden_field :idx %>
    </div>
    <div class="col-sm-1" style="margin-top: 5px;font-size: 18px;">
      <%= p.remove_nested_fields_link '<i class="fa fa-trash"></i>'.html_safe%>
    </div>
</div>
<% end %>
<%= f.add_nested_fields_link :products, "<i class='fa fa-plus'></i> product".html_safe%>

I want idx = 1 when first field created then 2 for the second one and so on. I have no idea to achieve this requirement, could you please give me some example or suggestion to implement this.

Hi, you can use the Index replacement string for this:

<%= p.hidden_field "id__nested_field_for_replace_with_index__", value: "__nested_field_for_replace_with_index__" %>

It is also mentioned in the readme.