Rails 4验证:在进行包含时将allow_nil放在何处?

 阳光明媚-在路上 发布于 2022-12-12 19:44

这两个实现在功能上是否相同?如果是这样,哪个"更好?"

  # from a model
  WIDGET_COLORS = %w(red yellow green)
  validates :widget_color,
           inclusion: {in: WIDGET_COLORS, allow_nil: true}

要么

  # from a model
  WIDGET_COLORS = %w(red yellow green)
  validates :widget_color,
           inclusion: {in: WIDGET_COLORS},
           allow_nil: true

更新:修复拼写错误,因此示例读取验证

1 个回答
  • 首先validatevalidates使用不同的方法-它应该是validates在这里.

    validates将搜索所提供的所谓哈希_validates_default_keys,这是一个内部数组[:if, :unless, :on, :allow_blank, :allow_nil , :strict].传递给validates此数组的所有参数都被视为使用此方法附加到模型的所有验证器的公共选项.所以,如果你这样做:

    validates :widget_color,
              inclusion: {in: WIDGET_COLORS},
              uniqueness: true,
              allow_nil: true
    

    allow_nil 会影响两个验证器,或相当于:

    validates :widget_color,
              inclusion: {in: WIDGET_COLORS, allow_nil: true},
              uniqueness: {allow_nil: true}
    

    另一方面用

    validates :widget_color,
              inclusion: {in: WIDGET_COLORS, allow_nil: true},
              uniqueness: true
    

    它只会影响它定义的验证器(在这种情况下InclusionValidator)

    2022-12-12 19:46 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有