Reputation: 3489
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 %>
Upvotes: 6
Views: 2016
Reputation: 15184
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 %>
Upvotes: 13
Reputation: 20639
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 %>
Upvotes: 0
Reputation: 2419
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.
Upvotes: 0