rails在模型中validation值是否在数组内

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

数组看起来像

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

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

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

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

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

 class Person < ActiveRecord::Base validates_inclusion_of :gender, :in => %w( mf ) ... end 

或者在你的情况下:

 validates_inclusion_of :type, in: @allowed_types 

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

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

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