Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto increment value in each loop

In code:

<% @offers.each do |offer|%>
  <%= offer.percentageOff%> <b>% OFF on order of</b>
  <%= image_tag('1407951522',:size=>'10x10',:alt=>'Rs.')%>
  <%= offer.amountforDiscount%>
  <%= button_to 'Delete',{:action=>'destroy',:id=>offer.id},class: "" %>
<% end %>

I am new in rails. I want to show all the offers in a numbered list, I can't use database table because id is not in order. For example:

  1. 30 % OFF on order of Rs.2000

  2. 13 % OFF on order of Rs.1000

How do i achieve this?

like image 829
John Avatar asked Feb 13 '23 00:02

John


1 Answers

Easiest way if you don't want to use each_with_index then You can define variable @count=0 and display, as loop occur it will be increment by 1

<% @count = 0 %>
<% @offers.each do |offer|%> 
<%= @count += 1 %> #I guess you want this to show Sr.No
...... # your code
<% end %>

each_with_index way :

<% @offers.each_with_index do |offer, index|%> 
 <%= index + 1 %> # index starts from 0, so added 1 to start numbering from 1
  ...... # your code
<% end %>
like image 193
Gagan Gami Avatar answered Feb 15 '23 10:02

Gagan Gami