简体   繁体   中英

Rails model validation - validates_inclusion_of

I have a string column in a table that can have a range of predefined values. It can also include a nil value. For ex: Dog, Cat, Bird, nil.

I want to write a validates_inclusion_of that checks to make sure all the values being entered fall within that predefined range. If, for ex, "Nasal Spray" is entered, it will throw an error.

What's the best way to do so?

Use the following validation within your model class:

validates_inclusion_of :animal, :in => %w(Dog Cat Bird), :allow_blank => true

—where :animal is the name of the column you want to validate.

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