Ruby-on-rails 即使存在未设置为 true,Rails 验证也需要数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7981351/
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
Rails validation required numericality even though presence is not set to true
提问by Hopstream
I'm trying to save a record which doesn't have one field set -- which has a validate numericality in the models. Even though the presence is not required in the validation, it's still throwing an error that the field is not a number.
我正在尝试保存没有一个字段集的记录——它在模型中具有验证数字。即使验证中不需要存在,它仍然会抛出该字段不是数字的错误。
Validation:
验证:
validates :network_id, :numericality => true
Code to that is saving model:
代码是保存模型:
networks.each do |network|
network.url = network.raw_data.link
network.save!
end
Error:
错误:
Validation failed: Network is not a number
回答by Unixmonkey
validates :network_id, :numericality => true, :allow_nil => true
回答by p.matsinopoulos
validates :network_id, :numericality => {:allow_blank => true}
回答by apneadiving
You should use allow_blank
你应该使用 allow_blank
validates :network_id, :numericality => true, :allow_blank => true
回答by sergserg
In Rails 4 (Ruby 2), you can write:
在 Rails 4 ( Ruby 2) 中,你可以这样写:
validates :network_id, numericality: { greater_than_or_equal_to: 0, allow_nil: true }
回答by thedanotto
You can also write like this...
也可以这样写...
validates_numericality_of :network_id, allow_nil: true

