[英]ruby on rails calculation total of table value
How can the total of a variable I define be calculated? 如何定义我定义的变量的总数?
I have: 我有:
product_sale.rb product_sale.rb
def totalprice
price*quantity
end
view 视图
%h1 Listing Product Sales
%table
%thead
%tr
%th Product name
%th Price
%th Quantity
%th Total price
%tbody
- @product_sales.each do |product_sale|
%tr
%td= product_sale.product_name
%td= product_sale.price
%td= product_sale.quantity
%td= product_sale.totalprice
%br
%h1
Total sum to be paid:
= Product_sale.sum(:totalprice)
the = Product_sale.sum(:totalprice)
does not work. = Product_sale.sum(:totalprice)
不起作用。 How can I calculate it? 我该如何计算?
@product_sales.map(&:totalprice).sum
@product_sales.sum('price * quantity') # single query, efficient
PS该类的正确名称是蛇形ProductSale
@product_sales.sum(&:totalprice)
我认为这应该适用于您只汇总所选产品销售总价的情况
@product_sales.sum('price * quantity')
Best solution for me was the one of Max: 对我来说最好的解决方案是Max的解决方案之一:
controller index view: @some_total = @product_sales.map(&:totalprice).sum
控制器索引视图:
@some_total = @product_sales.map(&:totalprice).sum
view: = @some_total
查看:
= @some_total
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.