简体   繁体   中英

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. 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. The below throws an error.

self.numbers = (1..10).to_a
validates_inclusion_of :valid_number, :in => numbers

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