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 money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
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)