Encapsulate each validation error as an Error object
Jun 17, 2020 , by Alkesh Ghorpade
2 minute read
Rails modified the way errors are represented
when a model save, create or update action fails.
Let’s say we have a User model, with columns like first_name, last_name, contact_number,
email and all of them are mandatory. If we try to create a User object without passing first_name
and contact_number as a string, the #errors function will show the errors as below
The error message for a particular field can be accessed using the  method as below
We could also use #messages or #full_messages to see the list of all errors.
Accessing errors in the above manner is not object oriented. If a particular
field has multiple errors associated, it has to be accessed using array indexes.
With recent changes in ActiveModel#errors class the above errors will appear as object of Error class
instead of hash.
We can now use where clause to fetch the error(s) related to a particular attribute.
We have methods like add, added?, delete, match? which have similar signature to
where => (attribute, type, options).
As seen above, we can verify presence of a specific error in a given attribute by using added? method.
With the new changes added, message or full_message method can be accessed using where clause.
Below methods are deprecated which will start showing deprecation warnings if used -