56

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?

Daniel
  • 861
  • 1
  • 8
  • 12

5 Answers5

52

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

vasylmeister
  • 521
  • 4
  • 3
  • Rails 5.2: `allow_blank` and `allow_nil` both work independently. You'll need to restart the web server if you're changing this code in your model.rb. – MSC Dec 13 '18 at 05:34
  • 3
    Rails 5.2: `allow_nil` does _not_ work either inside or outside the hash. `allow_blank` _does_ work. – tfwright Mar 12 '19 at 16:08
  • 2
    Note, the difference in placement affects the error message(s) generated when the the attribute fails validation. – jbarr Jun 06 '19 at 17:49
50

This syntax will perform inclusion validation while allowing nils:

validates :kind, :inclusion => { :in => ['a', 'b'] }, :allow_nil => true
Matt
  • 13,948
  • 6
  • 44
  • 68
  • Not 100% sure but I think allow_nil might need to be inside of the inclusion hash – aceofspades Jun 28 '13 at 14:39
  • 1
    The syntax is correct for Rails 3.2 (tested), I don't know if your suggestion might be valid for another version? – Matt Jun 28 '13 at 15:57
  • Perhaps. It looks wrong to me because it is really an exception to the inclusion requirement, which by itself would fail. If it works it works! – aceofspades Jun 28 '13 at 18:19
  • 2
    It's an exception to any validation, if the value is blank, no further validation is performed. – rewritten Oct 17 '13 at 15:12
9

check also :allow_blank => true

Oren
  • 976
  • 9
  • 23
3

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 } 
Fabrizio Regini
  • 1,500
  • 13
  • 26
2

In Rails 5.x you need, in addition to the following line, to call a before_validation method:

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

The before_validation is needed to convert the submitted blank value to nil, otherwise '' is not considered nil, like this:

  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.

W.M.
  • 589
  • 1
  • 6
  • 13