less than 1 minute read

When rendering a partial with a collection, it can be useful to know the index of the item currently being rendered. It turns out that rails provides this with an undocumented counter.

For example, say we want to render a collection of people who won a contest. We might have a template line like this:

<%= render :partial => "person", :collection => @winners %>

The person partial might look like:

Name: <%= person.name %>

Now, let’s say we want to add the person’s rank along with his/her name. Rails provides a local variable called ”#{partial_name}_counter” to provide the index of the currently rendered item in the collection. In our case, the variable is called person_counter. The counter starts at 0, so we’ll add 1 to it for a human readable ranking.

Now, our person partial looks like:

  Rank: <%= person_counter + 1 %>
  Name: <%= person.name %>

And the output is:

Rank: 1 Name: Peter
Rank: 2 Name: Paul
Rank: 3 Name: Mary

Update (6/20/08): Jan points out in the comments that the counter now starts at 1 in Rails 2.1.