Counters in partials, a little-known rails feature!

I don’t normally post rails tips that are New To Me, because I always feel like I’m late to the party and everyone knows the tip already. This one however, I vetted through some very experienced rails developers and it was new to them as well. Which is strange, because looking back, I think it was first added in 2004!

The feature I’m talking about is counters in partials used in a collection. Let me show you:

<%= render :partial => “book”, :collection => @books %>

As you know, that will loop through the array of @books and use the template _book.html.erb (by default) each time. Let’s take a look at that file and see how we can use the counter:

  Number: <%= book_counter %><br/>
  Title: <%= h book.title %><br/>
  Author: <%= h %><br/>

That will give us output like this:

  Number: 0<br/>
  Title: Promises in Death<br/>
  Author: J. D. Robb<br/>

  Number: 1<br/>
  Title: One Day at a Time<br/>
  Author: Danielle Steel<br/>

  Number: 2<br/>
  Title: First Family<br/>
  Author: David Baldacci<br/>

What’s this useful for?
I can think of two things off the top of my head:

  • Zebra Tables
  • Special classes for first or last elements to change them visually

Let me know here or on twitter (@kastner) if this was helpful (or any other little-known tips)