简体   繁体   中英

How to validate the inclusion of a list that contain two words

So I just figured out how to validate the inclusion of my select. However I have one problem that have risen. I'm unable to figure out how to validate it, if one of the values contain two words or more.

Take for example:

validates_inclusion_of :possibility, :in => %w(yes maybe no)

it would work perfectly. Yet if I have two, three words say:

validates_inclusion_of :job_possibility, :in => %w(yes please maybe not no thank you)

it wouldn't work. I've tried adding them into brackets etc. But been able to figure it out. Anybody know how to make this work?

You can do it by using %W instead of %w to achieve the required result. As %W supports String interpolation, you can easily implement the two words, three words, etc.

Using %W :

validates_inclusion_of :job_possibility, :in => %W(yes please #{"maybe not"} no #{"thank you"})

-Or-

you could just specify the array directly:

validates_inclusion_of :job_possibility, :in => ["yes", "please", "maybe not", "no", "thank you"]

For example:

In IRB,

 > job_possibility = %W(yes please #{"maybe not"} no #{"thank you"})
 ## => ["yes", "please", "maybe not", "no", "thank you"] 
 > job_possibility = ["yes", "please", "maybe not", "no", "thank you"]
 ## => ["yes", "please", "maybe not", "no", "thank you"] 

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