Rails: fields_for with index?
The answer is quite simple as the solution is provided within Rails. You can use f.options
params. So, inside your rendered _some_form.html.erb
,
Index can be accessed by:
<%= f.options[:child_index] %>
You don't need to do anything else.
Update: It seems that my answer wasn't clear enough...
Original HTML File:
<!-- Main ERB File -->
<% f.fields_for :questions do |builder| %>
<%= render 'some_form', :f => builder %>
<% end %>
Rendered Sub-Form:
<!-- _some_form.html.erb -->
<%= f.options[:child_index] %>
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 %>
As of Rails 4.0.2, an index is now included in the FormBuilder object:
https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-fields_for
For example:
<%= form_for @person do |person_form| %>
...
<%= person_form.fields_for :projects do |project_fields| %>
Project #<%= project_fields.index %>
...
<% end %>
...
<% end %>