Querying model errors in Rails 4

Updated . Posted . Visible to the public.

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 ...>

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.

Profile picture of Dominik Schöler
Dominik Schöler
Last edit
Daniel Straßner
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2015-05-27 09:30)