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!
validates_inclusion_of should work. For example:
validates_inclusion_of :attr, :in => [-5, -2, 2, 5], :allow_nil => true
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
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." }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With