RSS Feed
Feb 24

Counters in partials, a little-known rails feature!

Posted on Tuesday, February 24, 2009 in General

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)

Feb 7

A week into February

Posted on Saturday, February 7, 2009 in General

Feb 1

February 2009 Goals

Posted on Sunday, February 1, 2009 in General

Jan 28

I Kicked a Server – A Love story

Posted on Wednesday, January 28, 2009 in General

Jan 26

Tiny Goals

Posted on Monday, January 26, 2009 in General

Jan 25

Medium Business Blues

Posted on Sunday, January 25, 2009 in General

Jan 25

Why Summer School Rocked

Posted on Sunday, January 25, 2009 in General

Jan 23

New Theme, new day

Posted on Friday, January 23, 2009 in General

Jan 23

The problem with Girl Talk

Posted on Friday, January 23, 2009 in General

Jan 15

redirecting to a wordpress post based on custom fields

Posted on Thursday, January 15, 2009 in General