1
我有這個代碼與shipment has one invoice
一起使用,但現在我不得不將它更改爲shipment has many invoices
。我如何修改以下代碼以反映新的關聯?Rails 3.如何通過has_many關係使用reduce?
@totals = {
:overall => @shipments.reduce(0) { |total, shipment| total + shipment.invoice.customer_total },
:paid => @shipments.reduce(0) { |total, shipment| total + shipment.invoice.customer_amount_paid },
:balance => @shipments.reduce(0) { |total, shipment| total + shipment.invoice.customer_open_balance }
}
'reduce(0,:+)'是處理空數組所必需的。和'map' +'flatten(1)'='flat_map'。我確信這可以用SQL來完成,但這是一個很好的Ruby方法。 – tokland
@tokland非常好的一點。謝謝! – Kyle