rails validation: :allow_nil and :inclusion both needed at the same time

This syntax will perform inclusion validation while allowing nils:

validates :kind, :inclusion => { :in => ['a', 'b'] }, :allow_nil => true

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


check also :allow_blank => true


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 }