验证是否包含在选项数组中或为零 [英] Validate on inclusion within array of options OR be nil

查看:63
本文介绍了验证是否包含在选项数组中或为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,希望将字段的输入限制为nil或落在指定值数组之内。我可以使包含部分起作用,但是 allow_nil:true 的位对我似乎不起作用:

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

但无济于事。表达这种简单包含或nil组合的最简单方法是什么?

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

推荐答案

允许nil进行验证而又仍然允许的正确格式有限的值数组如下:

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 }

注意allow_nil选项是如何在内部包含选项哈希

notice how the allow_nil option is inside the inclusion option hash

这篇关于验证是否包含在选项数组中或为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆