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>)
(similarlyadd_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
[]
. Callsmessages[<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
tovalue
. 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
.