An Enum is a data type that allows us to define a set of named constants.
Rails 7.1 brings a notable enhancement to enum handling by introducing the :validate
option.
It will allow more flexible and robust validation of enum values within the ActiveRecord models.
In this blog post, we’ll explore how this change affects our code and how the validations for enum values were handled in previous versions of Rails.
Before
In previous versions of Rails, if we assign an incorrect value to the enum then
it used to raise an ArgumentError
.
We can illustrate this by the following example.
In the above snippet, we have a Holiday
model with an enum type
column which can take national
or regional
as valid holiday types.
When we tried passing optional
as a holiday type it raised an ArgumentError
.
After
Rails 7.1 introduced the validate
option for enums.
It will allow developers
to enforce the validation checks before saving enum values.
Let’s try passing the validate: true
to the above snippet and see the change introduced from this version.
We can also pass additional validation options
If we don’t pass the validate
option it will raise the ArgumentError
as in the earlier versions.
To know more about this feature, please refer to this PR