2012-02-20 59 views
0

我有一个视图帮助器,用于汇总行项目内的项目。每个订单可以有多个订单项。每个订单项都有不同的尺寸(字段)。对于下面的内容,我很好奇如何总结多个订单项的特定字段。查看帮助器以汇总订单项金额

def total_items(order) 
     xxs = order.lineitems.xxs.sum 
     return xxs 
end 

这是我有什么,但是当有一个订单多个行项目不工作,我怎样才能正确地写呢?

回答

1

这不是很明显的你问什么,但我想你想要的是这样的:

def total_items(order) 
    order.lineitems.inject(0) { |total, line_item| total + line_item.xxs } 
end 

这是什么方法呢,就是类似于这样:

def total_items(order) 
    total = 0; 
    order.lineitems.each do |line_item| 
     total += line_item.xxs 
    end 
    total 
end 

通过在Ruby中,return关键字是可选的。