세금 (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)
을 단지 있도록 내가 할 수있는 방법이 있나요? 그래서 오류 및 다음의 합이 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