ActiveRecord’s enum provides an easy way to map values to integers. However, it has been lagging in the built-in assertions available. Recently, Rails added options to prevent enum values from being defined erroneously. This does not covert the plethora of possible errors that can be encountered with enums.
Before
It was possible to set enum to empty values. This does not cause a drastic failure however it opens up a vulnerability. Further, it was also possible to define erroneous values to an enum like numbers or empty hashes.
Let’s see how the current implementation looks like. Consider this ActiveRecord model.
Let’s instantiate a new object.
As you can see an ArgumentError error is only thrown for erroneous values.
After
Thanks to this PR the missing assertions have been added.
Now let’s see what happens when instantiating a new object.
It preemptively catches errors now! Further, a clearer message is now given when setting enum values to Integer options.
This is what happens,
Prior to this change a generic error statement used to be raised which read
ArgumentError (Enum values ["abc", 1] must be either a hash, an array of symbols, or an array of strings.)
.
The updated error statement highlights the actual error in value setting.