我正在使用 RoR 3.2.11 编写计费系统。
现在我想计算账单的总金额。为此,我设计了这样的模型:
class Bill < ActiveRecord::Base
belongs_to :customer
has_many :bill_items, :dependent => :destroy
has_many :articles, :through => :bill_items
attr_accessible :date, :discount, :state, :category, :customer_id, :bill_items_attributes
accepts_nested_attributes_for :bill_items, :reject_if => lambda { |a| a[:count].blank? }, :allow_destroy => true
def total
bill_items.inject(0) { |acc, bill_items| acc + (bill_items.count * bill_items.article.price) } - discount
end
end
如果有东西存储在数据库中,那效果很好。如果“bill_item”为空,我会收到以下消息:
TypeError in Bills# edit
nil can't be coerced into Float
如果有人能帮我解决这个问题,那就太好了。