ActiveRecord comprises several pre-defined validation helpers that we can use directly within our class definitions. There are common validation rules that these helpers provide. This means that whenever a validation fails, an error will be added to the object’s errors collection, and this is related to the attribute getting validated.
We also have the liberty to add the same kind of validation to different attributes with a single line of code. This is because every helper accepts an arbitrary number of attribute names.
There are a vast number of helpers and numericality is one of them. This helper ensures that our attributes have only numeric values.
To understand how this validation works, first, we have to generate a table with JSON column(s)-
Earlier, Rails allowed the values to pass without any error, within the numericality validator, even when the value was not even an integer. Look at the example below to understand better -
Recently, Rails 7.0 introduced the only_numeric option to specify that only numeric options are allowed in the attributes. This method will, therefore, parse the value if it’s a string.
Look at the example below for a better understanding -
Since the data doesn’t usually get serialized automatically in JSON columns, Rails added this option within the numericality validator to solve the problem of correct data serialization.
For more discussion, please refer to this PR.