rails validation: :allow_nil and :inclusion both n

2019-06-14 20:46发布

Usually the field 'kind' should be allowed blank. but if it is not blank, the value should included in ['a', 'b']

validates_inclusion_of :kind, :in => ['a', 'b'], :allow_nil => true

The code does not work?

4条回答
淡お忘
2楼-- · 2019-06-14 21:22

In Rails 5 you can use allow_blank: true outside or inside inclusion block:

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

查看更多
做自己的国王
3楼-- · 2019-06-14 21:30

This syntax will perform inclusion validation while allowing nils:

validates :kind, :inclusion => { :in => ['a', 'b'] }, :allow_nil => true
查看更多
beautiful°
4楼-- · 2019-06-14 21:32

check also :allow_blank => true

查看更多
【Aperson】
5楼-- · 2019-06-14 21:32

If you are trying to achieve this in Rails 5 in a belongs_to association, consider that the default behaviour requires the value to exist.

To opt out from this behaviour you must specify the optional flag:

belongs_to :foo, optional: true 

validates :foo, inclusion: { in: ['foo', 'bar'], allow_blank: true } 
查看更多
登录 后发表回答