Ruby-on-rails rails 验证: :allow_nil 和 :inclusion 同时需要
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17359853/
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: :allow_nil and :inclusion both needed at the same time
提问by Daniel
Usually the field 'kind' should be allowed blank. but if it is not blank, the value should included in ['a', 'b']
通常应该允许字段“种类”为空。但如果它不为空,则该值应包含在 ['a', 'b'] 中
validates_inclusion_of :kind, :in => ['a', 'b'], :allow_nil => true
The code does not work?
代码不起作用?
回答by Matt
This syntax will perform inclusion validation while allowing nils:
此语法将在允许 nils 的同时执行包含验证:
validates :kind, :inclusion => { :in => ['a', 'b'] }, :allow_nil => true
回答by vasylmeister
In Rails 5 you can use allow_blank: trueoutside or inside inclusion block:
在 Rails 5 中,您可以使用allow_blank: true外部或内部包含块:
validates :kind, inclusion: { in: ['a', 'b'], allow_blank: true }
or
或者
validates :kind, inclusion: { in: ['a', 'b'] }, allow_blank: true
tip: you can use in: %w(a b)for text values
提示:您可以in: %w(a b)用于文本值
回答by Oren
check also :allow_blank => true
还检查:allow_blank => true
回答by Fabrizio Regini
If you are trying to achieve this in Rails 5 in a belongs_toassociation, consider that the default behaviour requires the value to exist.
如果您试图在 Rails 5 中以belongs_to关联方式实现这一点,请考虑默认行为要求该值存在。
To opt out from this behaviour you must specify the optionalflag:
要退出此行为,您必须指定optional标志:
belongs_to :foo, optional: true
validates :foo, inclusion: { in: ['foo', 'bar'], allow_blank: true }
回答by W.M.
In Rails 5.x you need, in addition to the following line, to call a before_validationmethod:
在 Rails 5.x 中,除了以下行之外,您还需要调用一个before_validation方法:
validates_inclusion_of :kind, :in => ['a', 'b'], :allow_nil => true
The before_validationis needed to convert the submitted blank value to nil, otherwise ''is not considered nil, like this:
将before_validation需要转换的提交空白值nil,否则''不认为nil,这样的:
before_validation(on: [:create, :update]) do
self.kind = nil if self.kind == ''
end
For database disk space usage it is of course better to store nil's than storing empty values as empty strings.
对于数据库磁盘空间的使用,存储nil's 比将空值存储为空字符串当然更好。

