I am a seasoned developer with over 9 years of experience in Ruby on Rails and Golang. My passion lies in tackling complex data structures and algorithm problems, always pushing myself to learn and grow. In my downtime, I find solace in the pages of books and the soothing sounds of a guitar. But I'm not just a one-trick pony! I love to stay active and challenge myself in other ways too. Whether it's on the football pitch, cricket field, table tennis table, or badminton court, I'm always up for some fun activities.
2 minute read
Rails modified the way errors are represented
when a model save, create or update action fails.
Before
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.
After
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.
NOTE
Below methods are deprecated which will start showing deprecation warnings if used -