2013-05-13 49 views
0

我想计算列中值的总和。例如:计算Ruby on Rails中的列值总和

@items = Item.find_all_by_cart_id(cart) 

项目具有列数量。我想要@items数量的总和。

+0

您是否尝试过使用[注](http://stackoverflow.com/questions/3728014/sum-the-value-of-array-in-hash) – 2013-05-13 13:59:33

回答

1
items_quantity = @items.map(&:quantity).sum 
1

试试这个

@items = Item.find_all_by_cart_id(cart).sum(:quantity) 
+0

这是一个更清洁,模型相关的方式来做到这一点。 – Gary 2014-08-29 04:20:49