rails在模型中验证值是否在数组内 [英] rails validate in model that value is inside array

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

问题描述

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

I have a form where i pass a field named :type and i want to check if it's value is inside an array of allowed types so that no one is allowed to post not-allowed types.

数组看起来像

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

我已经尝试使用 validates_exclusion_ofvalidates_inclusion_of,但似乎无法正常工作

i have tried using validates_exclusion_of or validates_inclusion_of but it doesn't seem to work

推荐答案

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

first, change the attribute from type to something else, type is a reserved attrubute name use for Single Table Inheritance and such.

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

这篇关于rails在模型中验证值是否在数组内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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