Read more

Querying model errors in Rails 4

Dominik Schöler
May 27, 2015Software engineer at makandra GmbH

ActiveModel supplies an errors object that behaves similar to a Hash. It can be used to add errors to a record, as well as to query the record for registered errors. This object is returned when calling <object>.errors:

errors = @user.errors # => #<ActiveModel::Errors ...>
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Here are some helpful messages of its API:


[<attribute name>]
: Returns an array of error messages on that attribute. Example: errors[:name] => ['is missing']


add_on_blank(<attribute list>) (similarly add_on_empty)
: Registers an error for each given attribute if it is blank?. Example: errors.add_on_blank(:name, :email, :address)


generate_message(<attribute>, <error type, e.g. :invalid>)
: Generates an error message for the given attribute. Will retrieve the error message from the locale files Show archive.org snapshot .


get(<attribute>)
: (Almost) an alias of []. Calls messages[<attribute>] and returns an array of error messages for that attribute.


include?(<attribute>)
: Returns whether there is an error message for that attribute.


set(<attribute>, <value>)
: Sets the error messages for attribute to value. It should be an array of error messages, but can technically be any object.


to_hash(<want full error messages prefixed with attribute name?>)
: Returns a hash of attribute: error_messages.

Posted by Dominik Schöler to makandra dev (2015-05-27 11:30)