Validating the Rails Model - validates_inclusion_of

I have a string column in a table that can have a range of predefined values. It may also include a nil value. For example: dog, cat, bird, zero.

I want to write validates_inclusion_of, which checks that all entered values ​​fall within this predefined range. If, for example, "Nasal Spray" is entered, it will give an error.

What is the best way to do this?

+4
source share
1 answer

Use the following check in the 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 check.

+6
source

Source: https://habr.com/ru/post/1314755/


All Articles