在示例 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)
失败?