Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a counter for an "each" loop in Rails?

How do I add a counter to an .each loop? Is there any easy way of doing this? I tried the below, but it does not seem to work.

<% @album.each do |e| %>
   <%= e %> #my_counter_does_not_work :)
   <%= link_to e.name, :controller => "images", :action => "album", :album_id => e.id, :album_name => e.name %>
<% end %>
like image 795
Francois Avatar asked Dec 01 '11 13:12

Francois


1 Answers

Use each_with_index : the index will automatically be your counter (but note it starts at 0 and not 1):

<% @album.each_with_index do |e, index| %>
  <%= link_to e.name, :controller => "images", :action => "album", :album_id => e.id, :album_name => e.name %>
<% end %>
like image 122
David Sulc Avatar answered Oct 11 '22 11:10

David Sulc