Ruby-on-rails :greater_than_or_equal_to in validates_numericality_of 仅部分适用于 rails 3.1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10198324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
:greater_than_or_equal_to in validates_numericality_of only partially working in rails 3.1
提问by user938363
We are using the following to check if stock_qty (an integer or a float. Could be zero but not nil) is greater or equal to zero:
我们正在使用以下内容来检查 stock_qty (整数或浮点数。可能为零但不为零)是否大于或等于零:
validates_numericality_of :stock_qty, :greater_than_or_equal_to => 0
validates_numericality_of :stock_qty, :less_than_or_equal_to => :in_qty, :if => Proc.new { |part| !part.in_qty.nil? }
:in_qty is a column in part model. This validation should allow positive or 0 for :stock_qty. The problem is that the rspec failed if :stock_qty is assigned zero. I noticed that :less_than_or_equal_to only allowed less_than and did not allow equal_to. Is there a way to validate the >= or <= in rails 3.1? Or what may go wrong with our validation code above. Thanks so much.
:in_qty 是零件模型中的一列。此验证应允许 :stock_qty 为正数或 0。问题是如果 :stock_qty 被分配为零,则 rspec 失败。我注意到:less_than_or_equal_to 只允许less_than 而不允许equal_to。有没有办法验证 rails 3.1 中的 >= 或 <= ?或者我们上面的验证代码可能出了什么问题。非常感谢。
回答by Eric Sites
try adding :only_integer => truelike so:
尝试添加:only_integer => true如下:
validates_numericality_of :stock_qty, :only_integer => true, :greater_than_or_equal_to => 0
EDIT
编辑
if this needs to pass when stock_qty is nil or zero you need to change your code to this:
如果这需要在 stock_qty 为零或零时通过,您需要将代码更改为:
validates_numericality_of :stock_qty, :allow_nil => true, :greater_than_or_equal_to => 0
validates_numericality_of :stock_qty, :allow_nil => true, :less_than_or_equal_to => :in_qty, :if => Proc.new { |part| !part.in_qty.nil? }
回答by rmagnum2002
validates :stock_qty, :numericality => { :only_integer => true, :greater_than_or_equal_to => 0 }
it works in my 3.1 app, in my case I have price, and when I update or add the product wthout price I got the "it's not a number" error, or something like that, but I can put a 0 in price column and it updates just fine. hope this helps.
它适用于我的 3.1 应用程序,在我的情况下我有价格,当我更新或添加没有价格的产品时,我得到了“它不是数字”错误,或者类似的错误,但我可以在价格列中输入 0 和它更新得很好。希望这可以帮助。
:greater_than_or_equal_to –Specifies the value must be greater than or equal to the supplied value. The default error message for this option is “must be greater than or equal to %{count}”.
:greater_than_or_equal_to –指定值必须大于或等于提供的值。此选项的默认错误消息是“必须大于或等于 %{count}”。
http://guides.rubyonrails.org/active_record_validations_callbacks.html
http://guides.rubyonrails.org/active_record_validations_callbacks.html
回答by jdoe
Also you could believe that there were 0 while there were nil. nilwon't pass this checking.
你也可以相信有 0 而有nil. nil不会通过这个检查。

