2012-09-05 4 views
1

세금 (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 

답변

3

또는 없을 것

3

당신은 map(&:amount)에 들어가되지 않습니다 compact 다음 all.map(&:tax) 후, 그것은 것입니다 빈 배열을 추가 할 수 있습니다 실제로는 tax_id 인 제품 만지도에 표시 할 수 있습니다. 다음과 같음 :

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