Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

8.8 Working with the Errors Hash

Some methods are provided to enable you to add validation errors to the collection manually and alter the state of the Errors object.

  • errors[:base] = msg Adds an error message related to the overall object state itself and not the value of any particular attribute. Make your error messages complete sentences, because Rails does not do any additional processing of them to make them readable.

  • errors[:attribute] = msg Adds an error message related to a particular attribute. The message should be a sentence fragment that reads naturally when prepended with the capitalized name of the attribute.

  • clear As you might expect, the clear method clears the state of the Errors object.

8.8.1 Checking for Errors

It’s also possible to check the Errors object for validation failures on specific attributes with a couple of methods, just using square brackets notation. An array is always returned; it’s an empty one when there aren’t any validation errors for the attribute specified.

>> user.errors[:login]
=> ["zed is already registered"]
>> user.errors[:password]
=> []

Alternatively, you could also access full error messages for a specific attribute using the full_messages_for method. Just like accessing validation failures for attributes using bracket notation, an array is always returned.

>> user.errors.full_messages_for(:email)
=> ["Email can't be blank"]
  • + Share This
  • 🔖 Save To Your Account