如果不存在关联,如何不求和



如果任何产品上都没有税(tax_id),我会得到错误undefined method 'amount' for nil:NilClass

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

我有没有办法做到这一点,如果在搜索所有产品时没有税务ID,它会将其显示为零,只执行self.sum(:amount)

或者,您可以确定产品的范围,只映射那些实际具有tax_id的产品。类似于:

self.sum(:amount) + self.where("tax_id IS NOT NULL").map(&:tax).map(&:amount).sum

您可以在all.map(&:tax)之后添加一个compact,然后它将是一个空数组,不会进入map(&:amount),因此没有错误,然后它的和将为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