Ask A Question

Notifications

You’re not receiving notifications from this thread.

add index to nested forms

Stan X asked in Rails

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%>
            <%end%>
    </div>
    <div class="actions">
  <%= f.submit "Enregistrer", class: "btn btn-primary float-right" %>
</div>
<% 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?

Reply

Looks like there's index method availalbe
https://apidock.com/rails/v4.0.2/ActionView/Helpers/FormHelper/fields_for

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 %>

Reply

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 ?

Reply

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);
}
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,329+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.