ruby-on-railsloopsfields-for

Rails: fields_for with index?


Is there a method (or way to pull off similar functionality) to do a fields_for_with_index?

Example:

<% f.fields_for_with_index :questions do |builder, index| %>  
  <%= render 'some_form', :f => builder, :i => index %>
<% end %>

That partial being rendered needs to know what the current index is in the fields_for loop.


Solution

  • The answer below was posted many years ago, for a modern approach see: https://stackoverflow.com/a/22640703/105403


    This would actually be a better approach, following Rails documentation more closely:

    <% @questions.each.with_index do |question,index| %>
        <% f.fields_for :questions, question do |fq| %>  
            # here you have both the 'question' object and the current 'index'
        <% end %>
    <% end %>
    

    From: http://railsapi.com/doc/rails-v3.0.4/classes/ActionView/Helpers/FormHelper.html#M006456

    It’s also possible to specify the instance to be used:

      <%= form_for @person do |person_form| %>
        ...
        <% @person.projects.each do |project| %>
          <% if project.active? %>
            <%= person_form.fields_for :projects, project do |project_fields| %>
              Name: <%= project_fields.text_field :name %>
            <% end %>
          <% end %>
        <% end %>
      <% end %>