简体   繁体   中英

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.

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.

I'm familiar with the Phrasing gem ; however, installing it seems overkill. (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_presence_of is from the Rails 1.x era and can only deal with the presence of something. 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.

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. As a note the official Rails documentation is usually a great place to start.

ActiveModel validates_inclusion_of怎么样?

validates_inclusion_of :subject, in: ['Learn Ruby', 'Learn Ruby on Rails'], message: 'Please select a valid Subject'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM