[英]Using Rails validations, how do I whitelist a phrase, e.g., “Learn Ruby”
I have validates_presence_of :subject, inclusion: { in: %w( 'Learn Ruby' 'Learn Ruby on Rails'), message: "Please select a valid Subject" }
Learn Ruby and Learn Ruby on Rails are examples of what I'm trying to do. 我有
validates_presence_of :subject, inclusion: { in: %w( 'Learn Ruby' 'Learn Ruby on Rails'), message: "Please select a valid Subject" }
学习Ruby和Learn Ruby on Rails就是我的例子试图做。
I've tried using single and double quotes without success. 我尝试使用单引号和双引号没有成功。
I've also tried an array: validates_presence_of :subject, inclusion: { in: ['Learn Ruby', 'Learn Ruby on Rails'], message: "Please select a valid Subject" }
without success. 我还尝试了一个数组:
validates_presence_of :subject, inclusion: { in: ['Learn Ruby', 'Learn Ruby on Rails'], message: "Please select a valid Subject" }
但没有成功。
I'm familiar with the Phrasing gem ; 我熟悉短语宝石 ; however, installing it seems overkill.
但是,安装它似乎过于矫kill过正。 (And, not having tried it, I'm not sure it will help here.)
(而且,如果没有尝试过,我不确定这里是否会有所帮助。)
It looks like you're mixing the old validates_x_y
type methods with the Rails 3.x validates
which is much more general purpose. 看起来您正在将旧的
validates_x_y
类型的方法与Rails 3.x validates
混合使用,这更加通用。
validates_presence_of
is from the Rails 1.x era and can only deal with the presence of something. validates_presence_of
来自Rails 1.x时代, 只能处理某些事物。 There's validates_inclusion_of
as a counterpart, but the real answer is to use the validates
call which can be configured to test for any number of things at once. 有
validates_inclusion_of
作为对应对象,但真正的答案是使用validates
调用,该调用可以配置为一次测试任意数量的事物。
The notation for that is: 表示为:
validates :subject,
inclusion: {
in: [
'Learn Ruby',
'Learn Ruby on Rails'
],
message: "Please select a valid Subject"
}
I've added some formatting as well to make what's going on more clear. 我还添加了一些格式,以使发生的事情更加清晰。 Those one-liners can get really tangled.
那些单调的人可能真的很纠结。
If your introduction is using those old-style validates_presence_of
methods it's out of date and you should look for a more recent version, or a better reference. 如果您的介绍使用的是那些老式的
validates_presence_of
方法,那么它已经过时了,您应该寻找更新的版本或更好的参考。 As a note the official Rails documentation is usually a great place to start. 注意,正式的Rails文档通常是一个很好的起点。
ActiveModel validates_inclusion_of
怎么样?
validates_inclusion_of :subject, in: ['Learn Ruby', 'Learn Ruby on Rails'], message: 'Please select a valid Subject'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.