Using a Rails collection partial with a counter

October 30, 2009

 
No Gravatar

I was reworking an application today and noticed there was a portion of the code that was rendering a counter.

# what I saw
<% @wheels.each_with_index do |wheel,count| %>
  <%= render :partial => "wheel", :locals => { :wheel => wheel, :count => count} %>
<% end %>
 
# you might also be doing
<% count =0 %>
<% @wheels.each do |wheel| %>
  <%= render :partial => "wheel", :locals => { :wheel => wheel, :count => count} %>
  <%= count += 1 %>
<% end %>

Instead of using a block and rendering the partial each time, let’s try something different. We’ll use:

<%= render :partial => "wheel", :collection => @wheels %>

This will allow us to iterate through each item in our @wheels collection. Rails will make each element available to the wheel partial using the “wheel” variable. If our partial was “book” our variable would be “book” as well. If you want to change the name of the variable, you can do this:

<%= render :partial => "wheel", :collection => @wheels, :as => "dinosaur" %>

Now that we’re rendering a collection, we have a helper available to us inside of the partial that returns the index. For example:

# in our view	
<%= render :partial => "wheel", :collection => @wheels %>
 
# in our wheel partial
# returns index
<%= wheel_count %>
 
# another example:
# in our view	
<%= render :partial => "page", :collection => @pages %>
 
# our page partial
# returns index
<%= page_count %>
blog comments powered by Disqus