【问题标题】:rails validate in model that value is inside arrayrails 在模型中验证值在数组内
【发布时间】:2012-08-17 01:37:04
【问题描述】:

我有一个表单,我在其中传递了一个名为 :type字段,我想检查它的值是否在允许的类型数组中,以便 不允许任何人发布不允许的类型

数组看起来像

@allowed_types = [
   'type1',
   'type2',
   'type3',
   'type4',
   'type5',
   'type6',
   'type7',
   etc...
]

尝试过使用 validates_exclusion_ofvalidates_inclusion_of,但它似乎不起作用

【问题讨论】:

    标签: ruby-on-rails arrays validation text model


    【解决方案1】:

    首先,将属性从 type 更改为其他内容,type 是用于单表继承等的保留属性名称。

    class Thing < ActiveRecord::Base
       validates :mytype, :inclusion=> { :in => @allowed_types }
    

    【讨论】:

      【解决方案2】:

      ActiveModel::Validations 为此提供了一个辅助方法。一个示例调用是:

      validates_inclusion_of :type, in: @allowed_types
      

      ActiveRecord::Base 已经是一个 ActiveModel::Validations,所以不需要包含任何东西。

      http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_inclusion_of

      另外,@RadBrad 是正确的,您不应该使用 type 作为列名,因为它是为 STI 保留的。

      【讨论】:

      • 虽然这有效,但它会导致 rubocop 违规: RuboCop:更喜欢新样式验证validates :column, inclusion: value 而不是validates_inclusion_of。 [Rails/验证]
      • 潜在编辑:Rails 现在提供了通过继承列覆盖 STI 表的能力。
      【解决方案3】:

      只给那些懒人(比如我)复制最新的语法:

      validates :status, inclusion: %w[pending processing succeeded failed]
      
      • validates_inclusion_of 自 Rails 3 以来已过期。
      • :inclusion=&gt; 哈希语法自 Ruby 2.0 以来已过时。
      • 赞成%w作为默认的字数组Rubocop option

      有变体:

      默认类型为常量:

      STATUSES = %w[pending processing succeeded failed]
      
      validates :status, inclusion: STATUSES
      

      OP的原文:

      validates :mytype, inclusion: @allowed_types
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-25
        • 2013-11-23
        • 1970-01-01
        • 2017-06-30
        • 2011-01-22
        相关资源
        最近更新 更多