简体   繁体   English

Ruby on Rails的每个方法都可以。

[英]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) 我在事件模型的显示页面上使用了此方法,并且能够以这种数组格式显示付款($ 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 付款1:$ 1000付款2:$ 4000付款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. 还有另一种与.each相似的方法,除了它还包含每次迭代的索引值。 It is called each_with_index . 它称为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. 请注意index + 1 ,因为数组是从零开始的,因此第一次付款将是索引0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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