undefined method 'amount' for nil:NilClass
如果税 ( tax_id
) 不存在于任何产品上,我会收到错误消息。
class Product < ActiveRecord::Base
attr_accessible :amount, :tax_id
belongs_to :tax
def self.total_with_tax
self.sum(:amount) + all.map(&:tax).map(&:amount).sum
end
end
class Tax < ActiveRecord::Base
attr_accessible :amount
has_many :products
end
有没有办法可以做到,所以如果在搜索所有产品时没有税号,它会将其呈现为 nil 并执行self.sum(:amount)
?