Andrew
Andrew

Reputation: 43113

Rails Validation: Limit input to specific values

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

Answers (3)

Joshua Pinter
Joshua Pinter

Reputation: 47481

Rails 3+

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

Peter Brown
Peter Brown

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

Costa Walcott
Costa Walcott

Reputation: 887

validates_inclusion_of should work. For example:

  validates_inclusion_of :attr, :in => [-5, -2, 2, 5], :allow_nil => true

Upvotes: 24

Related Questions