简体   繁体   中英

Ruby on Rails each do method.

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.

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 %>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM