Reputation: 45
I am having difficulty with a ruby method on my show page. I have two models: events, and payments. I am trying to show all payments made to a particular event.
I used this method on my show page on my events model and I was able to show the payments in array format like this ($1000 $4000 $2000)
<strong>Payments Made: </strong>
<% @event.payments.each do |p| %>
$<%= p.Payment_amount.to_s.reverse.gsub(/...(?=.)/,'\&,').reverse %>
<% end %>
What I would like is to show the payments like this:
Payment 1: $1000 Payment 2: $4000 Payment 3: $2000
I appreciate the help. Thanks, in advance.
Upvotes: 2
Views: 3828
Reputation: 11072
There's another method that is similar to .each
, except it also includes the index value at each iteration. It is called each_with_index
. You can use it in your scenario like so:
<% @event.payments.each_with_index do |payment, index| %>
Payment <%= index + 1%>: $<%= payment.Payment_amount.to_s.reverse.gsub(/...(?=.)/,'\&,').reverse %>
<% end %>
Note the index + 1
, since arrays are zero-based, and therefore the first payment will be index 0.
Upvotes: 1
Reputation: 16002
You can try this:
<strong>Payments Made: </strong>
<% @event.payments.each_with_index do |p, i| %>
Payment <%= i+1 %>: $<%= p.Payment_amount.to_s.reverse.gsub(/...(?=.)/,'\&,').reverse %>
<% end %>
Upvotes: 2