class MyModel < ActiveRecord::Base
has_many :things
end
model = MyModel.new
model.things.build do
#stuff...
end
model.things.sum(&:method)
#=> TypeError: nil can't be coerced into BigDecimal
model.things.class
#=> Array
model.things.to_a.sum(&:method)
#=> #<BigDecimal:7ff4d34ca7c8,'0.0',9(36)>
model.things.map(&:method).sum
#=> #<BigDecimal:7ff4d3373b40,'0.0',9(36)>
It seems in (Rails 3.2.8) that has_many
is creating collection.sum
.
According to the code, it will always try to hit the database using a SQL sum
.
However, in this particular instance, the model isn't saved. So there's nothing in
the database. I would think it should pull from the cached copy.
Also, there is the potential where the model
is saved, but the collection
was
modified but not saved yet (i.e. with a build
); this could cause un-expected
sums.
Yeah, line 10 seems like a bug.