Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate on inclusion within array of options OR be nil

I have a model where I'd like to restrict input for a field to either be nil or fall within a specified array of values. I can get the inclusion part working, but the allow_nil: true bit doesn't seem to work for me:

class Mock::Patient < ActiveRecord::Base
  LANGUAGE_OPTIONS = %w[English Spanish French German Chinese Hindi Punjabi]
  validates :preferred_language, inclusion: { in: LANGUAGE_OPTIONS }
end

I've tried modifying that last line to things like:

  validates :preferred_language, inclusion: { in: LANGUAGE_OPTIONS }, allow_nil: true

But to no avail. What's the simplest way to express this combination of simple inclusion or nil?

like image 306
idStar Avatar asked Nov 20 '12 02:11

idStar


1 Answers

the correct form to allow nil to validate while still allowing a limited array of values is the following:

validates :preferred_language, inclusion: { in: LANGUAGE_OPTIONS, allow_nil: true }

notice how the allow_nil option is inside the inclusion option hash

like image 96
LucaM Avatar answered Nov 16 '22 03:11

LucaM