在樣品的Rails 3.2.8應用(上紅寶石1.9.3)有以下簡單設置:導軌3收集`sum`失敗,類型錯誤
class Account < ActiveRecord::Base
has_many :line_items
def subtotal
line_items.sum(&:price)
end
end
class Line_Item < ActiveRecord::Base
belongs_to :product
def price
product.price * time
end
end
account = Account.new
account.line_items.build do |item|
item.years = 4
item.product = Product.last
end
account.subtotal
#=> TypeError: nil can't be coerced into BigDecimal
如以上所述subtotal
方法失敗,並轉換錯誤。在subtotal
我檢查了line_items.class
返回的類型,得到Array
。如果我更新的subtotal
的定義,下列任一,該方法的工作原理:
line_items.to_a.sum(&:price)
#=> #<BigDecimal:7ff4d34ca7c8,'0.0',9(36)>
line_items.map(&:price).sum
#=> #<BigDecimal:7ff4d3373b40,'0.0',9(36)>
爲什麼的line_items.sum(&:price)
初始定義失敗?
什麼類型(類)價格返回? line_items [0] .price.class? – Roger
它是'BigDecimal' –
奇怪。我運行1.9.3和Rails 3.2.1,但它工作正常。你確定所有記錄都返回同一個班級嗎?也許循環的價格,並檢查每個類。 – Roger