1

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)

4

2 回答 2

3

或者,您可以将产品范围限定为仅映射那些实际具有tax_id. 就像是:

self.sum(:amount) + self.where("tax_id IS NOT NULL").map(&:tax).map(&:amount).sum
于 2012-09-05T01:57:42.053 回答
3

您可以compactall.map(&:tax)then 之后添加一个,它将是一个空数组,它不会进入map(&:amount)so no 错误,然后它的总和将为 0。

self.sum(:amount) + all.map(&:tax).compact.map(&:amount).sum

>> [nil].map(&:amount).sum
# NoMethodError: undefined method `amount' for nil:NilClass
>> [nil].compact.map(&:amount).sum
#=> 0
于 2012-09-05T00:35:34.307 回答