サンプル Rails 3.2.8 アプリ (Ruby 1.9.3 上) には、次の簡単なセットアップがあります。
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)
の最初の定義が失敗するのはなぜですか?