[英]Ruby on Rails - Validates_inclusion_of in an array
I'm trying to create validations, where it only allows values that are in an array. 我正在尝试创建验证,该验证仅允许数组中的值。
validates_inclusion_of :valid_number, :in =>[1,2,3,4,5,6,7,8,9,10]
That works, but what I want is something like this 那行得通,但是我想要的是这样的东西
numbers = [1,2,3,4,5,6,7,8,9,10]
validates_inclusion_of :valid_number, :in => numbers
When I type that I always get a NoMethodError. 当我键入时,我总是得到一个NoMethodError。 This leads me to believe maybe I need a different type of variable (instance, class, global).
这使我相信也许我需要其他类型的变量(实例,类,全局)。
Just a heads-up, I know there's a way to validate numericality in a range, but that's not what I'm looking for. 只是一个提示,我知道有一种方法可以验证范围内的数值,但这不是我想要的。 I just picked numbers because it was quicker to type.
我选择数字是因为它可以更快地键入。
Should be able to make it a constant: 应该能够使其成为常数:
NUMBERS = (1..10).to_a
validates_inclusion_of :valid_number, :in => NUMBERS
This might work as well, but i haven't tested :) 这可能也可以,但是我还没有测试过:)
Edit Nope, doesn't work. 编辑 Nope,不起作用。 The below throws an error.
下面抛出一个错误。
self.numbers = (1..10).to_a
validates_inclusion_of :valid_number, :in => numbers
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.