In Ruby on Rails, how can I access the iteration counter within a loop?
The following works, but using the child_number variable is a bit of a hack. Is there a better way of achieving this?
<% 5.times { @parent.child.build } %>
<%= form_for @parent do |parent_form| %>
<p>
<%= parent_form.label :full_name, "Parent's name" %>
<%= parent_form.text_field :full_name %>
</p>
<%= parent_form.fields_for :children do |child_form| %>
<% @child_number ||= 1 %>
<p>
<%= child_form.label :full_name, "Child #{@child_number}'s name" %>
<%= child_form.text_field :full_name %>
</p>
<% @child_number += 1 %>
<% end %>
<p>
<%= parent_form.submit %>
</p>
<% end %>
Well, it’ll be in the Rails 3.2 – https://github.com/rails/rails/pull/1189
It’ll be look like https://github.com/jmbejar/rails/commit/7c562d5e460d97b18e4f3367b3cfb13401732920
Now you can use something like that: