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

すべての商品を検索するときにTaxIDが存在しない場合、nilとしてレンダリングされ、そのまま実行されるようにする方法はありますself.sum(:amount)か?

4

2 に答える 2

3

compactその後にaを追加するall.map(&:tax)と、空の配列になります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
于 2012-09-05T00:35:34.307 に答える
3

または、製品のスコープを設定して、実際に。を持つ製品のみをマップすることもできますtax_id。何かのようなもの:

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