How to use inject to get sum of some AR collection?

activerecord, ruby

Solution

Unless you pass initial value to `Enumerable#inject`, the first item of the collection is used (`OrderItem` in you case).; `OrderItem += OrderItem#value` returns OrderItem according to your question.

Try the following (explicitly pass the initial value as Fixnum `0`):

order_items.inject(0) { |sum, oi| sum + oi.value }

As bjhaid commented, it's better to use `sum` method provided by ActiveRecord if you dealing with ActiveRecord. (Does not require to fetch records)

OrderItem.sum('value')

Problem

There is model Order with association OrderItem. I need to calculate order's cost, and I use for it the following code: ``` order_items.inject{ |sum, oi| sum += oi.value } ``` But as result I get OrderItem object, not Fixnum or something else. What do I wrong?

Original source