Validate on inclusion within array of options OR be nil

大城市里の小女人 提交于 2019-12-13 11:57:04

问题


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?


回答1:


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




回答2:


I solved this by making the validates line look like this:

validates :preferred_language, inclusion: { in: LANGUAGE_OPTIONS + [nil] }

This way, I allow nil, but I don't change the constant I use in my view for feeding the collection of select options. I've since also prepended the array with an element '' so I don't have to explicitly include blank in my form input helper.



来源:https://stackoverflow.com/questions/13465691/validate-on-inclusion-within-array-of-options-or-be-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!