Reputation: 43113
I'm looking for "the Rails Way" to write a validation that limits acceptable input values to a predetermined list.
In my case, I want to only accept the values "-5", "-2", "+2", "+5", and nil. However, I think this is best as a general question: how do you predefine a list of acceptable entry values in a Rails model?
Thanks!
Upvotes: 17
Views: 8311
Reputation: 47481
The modern way to do this is the following:
validates :field, inclusion: { in: [ -5, -2, 2, 5 ], allow_blank: true, message: "not an allowable number." }
Upvotes: 3
Reputation: 51697
You want to use validates_inclusion_of with the :in
and :allow_nil
options.
validates_inclusion_of :field, :in => %w(-5 -2 2 5), :allow_nil => true
You'll probably also want to use in conjunction with validates_numericality_of
Upvotes: 11
Reputation: 887
validates_inclusion_of should work. For example:
validates_inclusion_of :attr, :in => [-5, -2, 2, 5], :allow_nil => true
Upvotes: 24