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:
<div>
Number: <%= book_counter %><br/>
Title: <%= h book.title %><br/>
Author: <%= h book.author %><br/>
</div>
That will give us output like this:
<div>
Number: 0<br/>
Title: Promises in Death<br/>
Author: J. D. Robb<br/>
</div>
<div>
Number: 1<br/>
Title: One Day at a Time<br/>
Author: Danielle Steel<br/>
</div>
<div>
Number: 2<br/>
Title: First Family<br/>
Author: David Baldacci<br/>
</div>
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)