Sometimes I like to number rows using a counter when rendering lists of things:

<% @products.each_with_index do |product, i| %>
<li class="product_<%= i %>"><%= product.name %></li>
<% end %>

They are handy for testing, among other things.

Of course, if the content of the block gets too big I’ll factor it out into a partial. The idiomatic Rails way of doing this is to factor the block contents out into a partial and then render it with the :collection option:

<%= render :partial => "product", :collection => @products %>

Which is very clean, except now where do we get our row counter? As it turns out, Rails provides one for us:

  <li class="product_<%= product_counter %>"><%= product.name %></li>

Note the use of product_counter. Rails takes the name of the partial and adds _counter to it when providing the built-in counter.

Just be aware that unlike the counter provided by each_with_index, this counter is 1-based. I have seen some references to this counter being 1-based, but at least in the version of Rails I am using (2.3.9) the counter is 0-based.

Published by Avdi Grimm

2 Comments

  1. Nice tip! Thanks for this!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *