Ruby on Rails nil can't be coerced into BigDecimal

后端 未结 2 890
日久生厌
日久生厌 2020-12-17 00:55

Why do I get nil can\'t be coerced into BigDecimal when I try to perform a calculation: here\'s the code:

model/drink.rb



        
2条回答
  •  无人及你
    2020-12-17 00:59

    If you want nil to be evaluated as 0.0 then you can do something like this:

    def total_amount
        self.total_amount = self.price.to_s.to_d * self.quantity.to_s.to_d
    end 
    

    Or explicitly check for nil

    def total_amount
      if self.price && self.quantity
        self.total_amount = self.price * self.quantity
      else
        self.total_amount = "0.0".to_d
      end
    end 
    

    The problem is really that your record fields aren't set like you expect them to be. Do you need to use validations to make sure that the price and quantity fields are set?

    class Drink
      validates :price, :presence => true      # Don't forget add DB validations, too :)
      validates :quantity, :presence => true
    end
    

    That way you ensure that you don't get a nil value when calling #total_amount.

提交回复
热议问题