Skip to main content

add index to nested forms

Rails • Asked by Stan X

Hi guys.

currently struggling to retrieve child index reference in nested forms.
I have my main form:

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put, class: 'form-horizontal' }) do |f| %>
<%= render 'shared/devise_errors' %>
<div id="profiles">
            <%= f.fields_for :profiles do |profile_form| %>
                <%= render 'profile_fields', f: profile_form%>
    <div class="actions">
  <%= f.submit "Enregistrer", class: "btn btn-primary float-right" %>
<% end %>

and sub form _profile_fields.html.erb:

<div class="card text-justify" >

  <div class="card-header">
    <h4 class="card-title">
      <%indexi = f.options[:child_index].to_i+1 %>
      <%index= indexi.to_s %>
      <div class="form-group row">
        <%= f.label :label, class:'info col-md-4 col-form-label'%>
        <div class="input-group col-md-8">
          <%= f.text_field :label, class: "form-control", placeholder: "Profile #{index}",:value:(f.object.label || "Profile #{index}") %>


this index is stuck to same figure when I add some new profile forms (child of user).

I probaby have to refactor but unclear how. seems to me that many have experienced a similar issue in the past. answers not really clear. is there anything missing in rails to be able to do this in an easy way?

Looks like there's index method availalbe

So it should work like this:

<%= form_for @person do |person_form| %>
<%= person_form.fields_for :projects do |project_fields| %>
Project #<%= project_fields.index %>
<% end %>
<% end %>

In your case you should be able to pass it, like:
<%= render 'profile_fields', f: profile_form, i: profile_form.index %>

thks Jack.

I changed it for:

  <%= render partial:'profile_fields', locals: {f: profile_form, i: profile_form.index}%>

but receiving a

undefined local variable or method `i' for #<#Class:0x,...
for my subform line:

    <%= f.text_field :label, class: "form-control", placeholder: "Profile #{i}" %>

presumably profile_form.index is not defined ?

Seems strange to me. In the meantime, I found a workaround using CSS.

this is the top of my sub-form:
<section><%= f.label :label, class:'info col-md-4 col-form-label'%></section>

and this is the CSS added:

body {
  counter-reset: section;
section {
  counter-increment: section;
  white-space: nowrap;
  overflow: hidden;
section label:after {
  content: ' ' counter(section);

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.