rails在模型中验证值是否在数组内部

fxu*_*ser 20 arrays validation text model ruby-on-rails

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

数组看起来像

@allowed_types = [
   'type1',
   'type2',
   'type3',
   'type4',
   'type5',
   'type6',
   'type7',
   etc...
]
Run Code Online (Sandbox Code Playgroud)

尝试使用 validates_exclusion_ofvalidates_inclusion_of但似乎没有用

小智 42

首先,将属性从type更改为其他类型,type是用于单表继承的保留attrubute名称等.

class Thing < ActiveRecord::Base
   validates :mytype, :inclusion=> { :in => @allowed_types }
Run Code Online (Sandbox Code Playgroud)


Cal*_*son 20

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

class Person < ActiveRecord::Base
    validates_inclusion_of :gender, :in => %w( m f )
   ...
end
Run Code Online (Sandbox Code Playgroud)

或者在你的情况下:

validates_inclusion_of :type, in: @allowed_types
Run Code Online (Sandbox Code Playgroud)

ActiveRecord :: Base已经是ActiveModel :: Validations,因此不需要包含任何内容.

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

此外,@ RadBrad是正确的,您不应将其type用作列名,因为它是为STI保留的.


Yi *_*eng 7

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

validates :status, inclusion: %w[pending processing succeeded failed]
Run Code Online (Sandbox Code Playgroud)
  • validates_inclusion_of 自 Rails 3 以来已过时。
  • :inclusion=> hash 语法从 Ruby 2.0 开始就已经过时了。
  • 赞成%wfor word array 作为默认的Rubocop 选项

有变化:

默认类型为常量:

STATUSES = %w[pending processing succeeded failed]

validates :status, inclusion: STATUSES
Run Code Online (Sandbox Code Playgroud)

OP原文:

validates :mytype, inclusion: @allowed_types
Run Code Online (Sandbox Code Playgroud)