Skip to content

Instantly share code, notes, and snippets.

@cupakromer
Created October 12, 2012 15:20
Show Gist options
  • Save cupakromer/3879718 to your computer and use it in GitHub Desktop.
Save cupakromer/3879718 to your computer and use it in GitHub Desktop.
WTF rails?
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.

@steveklabnik
Copy link

Yeah, line 10 seems like a bug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment