Validate on inclusion within array of options OR be nil

前端 未结 2 1978
离开以前
离开以前 2021-02-20 02:45

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 all

2条回答
  •  醉酒成梦
    2021-02-20 03:25

    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.

提交回复
热议问题