2

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.

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

That doesn't work, I get undefined local variable or method numbers. Do we need an @ symbol before the variable name or make self.numbers a method? Of course, I also had my validates statement before the numbers statement. Should it be the other way around? Never mind, that doesn't work either.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.