I have 10 form fields and I want to append a number next to each field, going sequentially from 1 to 10. The problem is that the code is already in a loop. It’s inside a partial, and the partial is passed a collection.
<%= fields_for "list", f do |f| %>
<!-- I want 1, 2, etc to appear here depending on the iteration. -->
<%= f.label :name %>
I tried using <%= i += 1 %> but it does not work since i is not defined. If I define i, it will keep getting reset to the same number, so it makes no difference. Any ideas?
Rails automatically defines a local variable called
partialname_counterwhere, obviously, “partialname” is the name of your partial. So if your partial is called e.g._list_item.html.erbyou could write it like this:(The
+ 1, of course, is there because the counter starts at0.)Another option would be to just let the browser do the numbering for you using an ordered list:
In the view:
…and in the partial:
This option is probably more semantic, and lists are easy to style in CSS.