简体   繁体   English

Rails:nil:NilClass 的未定义方法“*”

[英]Rails: undefined method `*' for nil:NilClass

I am newbie to rails and want to do basic maths in model to get selling price from some maths.我是 Rails 的新手,想在模型中进行基本数学运算,以便从一些数学运算中获得售价。 I am writing a simple equation in product model.我在产品模型中写了一个简单的方程。 Here is it:就这个:

 def selling_price
  foodio_price + (foodio_price*@@tax) + @@dc
 end

But it is giving error- undefined method `*' for nil:NilClass.但是它为 nil:NilClass 给出了错误未定义的方法 `*'。 It is not recognizing * for multiplication as well as + for sum.它不能识别乘法的 * 以及和的 +。 Can anybody tell what's wrong here?任何人都可以告诉这里有什么问题吗?

One of your variables in that function (like foodio_price or @@tax ) is nil .该函数中的变量之一(如foodio_price@@tax )是nil Everything in Ruby is an object, even including nil , which you may know in other programming languages as null . Ruby 中的一切都是对象,甚至包括nil ,您在其他编程语言中可能将​​其称为null Every instance of nil inherits from the class NilClass . nil每个实例都继承自NilClass类。 Hence, nil:NilClass is referring to an instance of nil which is of type NilClass .因此, nil:NilClass指的是nil一个实例,它的类型是NilClass

To debug this issue you can check which (or al three) of these values is nil by adding puts statements.要调试此问题,您可以通过添加puts语句来检查这些值中的哪些(或三个) nil


My guess is that both @@tax and @@dc are nil . 我的猜测是@@tax@@dc都是nil Rarely do you need to use these class variables in Rails. 您很少需要在 Rails 中使用这些类变量。 I'd suggest just declaring the tax and dc as constants, so something like 我建议只将taxdc声明为常量,所以像

TAX = 0.09 DC = 0.10

somewhere in your class file.在你的类文件中的某个地方。


For default values on a nil parameter for foodio_price 对于foodio_pricenil参数的默认值

def selling_price foodio_price if foodio_price.nil? return 0.0 foodio_price + (foodio_price*@@tax) + @@dc end

The error is saying the foodio_price is an object from NilClass class错误是说 foodio_price 是来自 NilClass 类的对象

In pseudo code, foodio_price = nil在伪代码中,foodio_price = nil

Your variable foodio_price is not instancied (don't have any value yet)您的变量 foodio_price 未实例化(尚无任何值)

You should try this你应该试试这个

def selling_price(foodio_price)
  foodio_price + (foodio_price*@@tax) + @@dc
end

And in other places of your code, where you call the function selling_price , you pass it the parameter foodio_price在代码的其他地方,您调用函数selling_price ,将参数foodio_price传递给它

it worked.有效。 Changed my model to:将我的模型更改为:

 def selling_price
  self.foodio_price  ||= 0.0  
  foodio_price + (foodio_price*@@tax) + @@dc
 end
foodio_price + ((foodio_price || 1)*(@@tax || 1|) + (@@dc || 0)

试试这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM