在每个“每次执行"中,在Rails中进行基本数学运算.循环并求和 [英] Doing basic math in Rails within each "each do" loop and getting the sum
问题描述
Rails的新手!我有与广告系列相关的产品.每个@product都有一个与其关联的.price和.orders_count.
New to Rails! I have products which are associated to a campaign. Each @product has a .price and .orders_count associated to it.
我想做的是将每个@product的.price与.orders_count相乘,并将它们全部相加,以得出@campaign的总费用.
What I wanted to do is multiply the .price with .orders_count for each @product, and add them all up to get a total cost for the @campaign.
对Rails陌生,不确定如何执行写语法,并且在视图中具有以下内容.这是第一部分,但不会在最后将它们全部加在一起.感谢您的帮助!
Being new to Rails, wasn't sure how to do the write syntax and had the following in the view. This does the first piece, but does not add them all up at the end. Thanks for the help!
<% @products.each do |p| %>
<% if p.orders_count? %>
<%= (number_to_currency((p.price) * p.orders_count)) %>
<% end %>
<% end %>
推荐答案
尝试设置变量以跟踪所有乘积的总和,并在每次循环时将乘积添加到该乘积中.试试这个:
Try setting a variable to keep track of the sum of all products, and add the product to it each time through the loop. Try this:
<% sum = 0 %>
<% @products.each do |p| %>
<% if p.orders_count? %>
<% product = (number_to_currency((p.price) * p.orders_count)) %>
<% sum += product %>
<%= product %>
<% end %>
<% end %>
The sum is: <%= sum %>
这篇关于在每个“每次执行"中,在Rails中进行基本数学运算.循环并求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!