6

I've got a list of items I'm looping in an each in my show view. This is all perfectly fine. However, I would like to get a number infront of each item which increments with every loop ( i = 0, i++ you know the drill ).

Now, how can i do this in Rails? This is what I get by now:

<% i = 0 %>
<% @trip.triplocations.each do |tl| %>
  <article id="<%= dom_id(tl)  %>">
    <strong> <%= tl.title %> </strong>
      <p>
        <%= tl.description %>
      </p>
  </article>
<% end %>
waldyr.ar
  • 14,424
  • 6
  • 33
  • 64
CaptainCarl
  • 3,411
  • 6
  • 38
  • 71

3 Answers3

13

Use #each_with_index instead of instantiating a variable in view!

<% @trip.triplocations.each_with_index do |tl, i| %>
  <article id="<%= dom_id(tl) %>">
    <strong> <%= i %>. <%= tl.title %> </strong>
      <p>
        <%= tl.description %>
      </p>
  </article>
<% end %>
waldyr.ar
  • 14,424
  • 6
  • 33
  • 64
  • That certainly worked! However; is it possible to start the i at 1? Since i want to use it as a visual numbering. – CaptainCarl Oct 13 '12 at 06:16
  • 3
    You can increase by 1 like this `<%= i+1 %>`. This should work but for more information take a look at [HERE](http://stackoverflow.com/questions/5646390/ruby-each-with-index-offset). – waldyr.ar Oct 13 '12 at 06:17
0

Probably you want this sort of code.

<% i = 0 %>
<% @trip.triplocations.each do |tl| %>
    <article id="<%= dom_id(tl)  %>">
        <strong> <%= tl.title %> </strong>
        <p>
            <%= i %>
            <%= tl.description %>

        </p>
    </article>
    <% i = i + 1 %> 
<% end %>

Note:

You can place the code

<%= i %>

anywhere you want inside the loop.

RAM
  • 2,413
  • 1
  • 21
  • 33
0

There is no ++ operator in Ruby. Instead you use += 1:

array = 'a'..'d'

i = 0
array.each do |element|
  puts "#{i} #{element}"
  i += 1
end

Prints

0 a
1 b
2 c
3 d

However, you should not do that because there is already a convenient method for that:

array = 'a'..'d'

array.each_with_index do |element, i|
  puts "#{i} #{element}"
end

There is another way of doing that specific to Rails. If you render collection using a partial you will have object_counter variable available where "object" is your model name. For example:

<%= render @trip.triplocations %>

<% # in views/triplocations/_triplocation.html.erb %>
<%= triplocation_counter %>
<%= triplocation.title %>
Simon Perepelitsa
  • 20,350
  • 8
  • 55
  • 74