class ActiveModel::Errors
# etc..
person.errors.full_messages # => [“name cannot be nil”]
person.validate! # => [“cannot be nil”]
person = Person.new
The above allows you to do:
for you.ActiveModel::Validations
will handle the validation related methods
you will not need to implement the last two. Likewise, using
languages. Of course, if you extend your object with ActiveModel::Translation
able to generate error messages correctly and also handle multiple
The last three methods are required in your object for Errors
to be
end
end
[self]
def self.lookup_ancestors
end
attr
def self.human_attribute_name(attr, options = {})
end
send(attr)
def read_attribute_for_validation(attr)
# The following methods are needed to be minimally implemented
end
errors.add(:name, :blank, message: “cannot be nil”) if name.nil?
def validate!
attr_reader :errors
attr_accessor :name
end
@errors = ActiveModel::Errors.new(self)
def initialize
extend ActiveModel::Naming
# Required dependency for ActiveModel::Errors
class Person
A minimal implementation could be:
for handling error messages and interacting with Action View helpers.
Provides a modified Hash
that you can include in your object
== Active Model Errors
def [](attribute)
person.errors[:name] # => []
person.errors.keys # => []
of error keys which includes this attribute.
an empty error list for it and +keys+ will return an array
no errors associated with it, this method will instantiate
Note that, if you try to get errors of an attribute which has
person.errors['name'] # => ["cannot be nil"]
person.errors[:name] # => ["cannot be nil"]
for the method.
When passed a symbol or a name of a method, returns an array of errors
def [](attribute) messages[attribute.to_sym] end
def add(attribute, message = :invalid, options = {})
person.errors.details
# => {:base=>["either name or email must be present"]}
person.errors.messages
message: "either name or email must be present")
person.errors.add(:base, :name_or_email_blank,
directly associated with a single attribute.
+attribute+ should be set to :base if the error is not
person.errors.messages # => {}
# => NameIsInvalid: Name is invalid
person.errors.add(:name, :invalid, strict: NameIsInvalid)
# => ActiveModel::StrictValidationFailed: Name is invalid
person.errors.add(:name, :invalid, strict: true)
:strict option can also be set to any other exception.
ActiveModel::StrictValidationFailed instead of adding the error.
If the :strict option is set to +true+, it will raise
Time.now to be used within an error.
If +message+ is a proc, it will be called, allowing for things like
scope (see +generate_message+).
If +message+ is a symbol, it will be translated using the appropriate
# => {:name=>[{error: :not_implemented}, {error: :invalid}]}
person.errors.details
# => {:name=>["is invalid", "must be implemented"]}
person.errors.messages
# => ["is invalid", "must be implemented"]
person.errors.add(:name, :not_implemented, message: "must be implemented")
# => ["is invalid"]
person.errors.add(:name)
If no +message+ is supplied, :invalid is assumed.
More than one error can be added to the same +attribute+.
Adds +message+ to the error messages and used validator type to +details+ on +attribute+.
def add(attribute, message = :invalid, options = {}) message = message.call if message.respond_to?(:call) detail = normalize_detail(message, options) message = normalize_message(attribute, message, options) if exception = options[:strict] exception = ActiveModel::StrictValidationFailed if exception == true raise exception, full_message(attribute, message) end details[attribute.to_sym] << detail messages[attribute.to_sym] << message end
def added?(attribute, message = :invalid, options = {})
person.errors.added? :name, :too_long # => false
person.errors.added? :name, :too_long, count: 24 # => false
person.errors.added? :name, "is too long (maximum is 25 characters)" # => true
person.errors.added? :name, :too_long, count: 25 # => true
person.errors.add :name, :too_long, { count: 25 }
the correct option, or +false+ with an incorrect or missing option.
If the error message requires an option, then it returns +true+ with
person.errors.added? :name, "can't be blank" # => true
person.errors.added? :name, :blank # => true
person.errors.add :name, :blank
present, or +false+ otherwise. +message+ is treated the same as for +add+.
Returns +true+ if an error on the attribute with the given message is
def added?(attribute, message = :invalid, options = {}) message = message.call if message.respond_to?(:call) message = normalize_message(attribute, message, options) self[attribute].include? message end
def apply_default_array(hash)
def apply_default_array(hash) hash.default_proc = proc { |h, key| h[key] = [] } hash end
def as_json(options = nil)
person.errors.as_json # => {:name=>["cannot be nil"]}
if the json object should contain full messages or not (false by default).
object. You can pass the :full_messages option. This determines
Returns a Hash that can be used as the JSON representation for this
def as_json(options = nil) to_hash(options && options[:full_messages]) end
def clear
person.errors.clear
person.errors.full_messages # => ["name cannot be nil"]
Clear the error messages.
def clear messages.clear details.clear end
def copy!(other) # :nodoc:
person.errors.copy!(other)
Examples
other - The ActiveModel::Errors instance.
Copies the errors from other.
def copy!(other) # :nodoc: @messages = other.messages.dup @details = other.details.dup end
def delete(key)
person.errors.delete(:name) # => ["cannot be nil"]
person.errors[:name] # => ["cannot be nil"]
Delete messages for +key+. Returns the deleted messages.
def delete(key) attribute = key.to_sym details.delete(attribute) messages.delete(attribute) end
def each
# then yield :name and "must be specified"
# Will yield :name and "can't be blank"
person.errors.each do |attribute, error|
person.errors.add(:name, :not_specified, message: "must be specified")
end
# Will yield :name and "can't be blank"
person.errors.each do |attribute, error|
person.errors.add(:name, :blank, message: "can't be blank")
has more than one error message, yields once for each error message.
Yields the attribute and the error for that attribute. If the attribute
Iterates through each error key, value pair in the error messages hash.
def each messages.each_key do |attribute| messages[attribute].each { |error| yield attribute, error } end end
def empty?
person.errors.full_messages # => ["name cannot be nil"]
If the error message is a string it can be empty.
Returns +true+ if no errors are found, +false+ otherwise.
def empty? size.zero? end
def full_message(attribute, message)
Returns a full message for a given attribute.
def full_message(attribute, message) return message if attribute == :base attr_name = attribute.to_s.tr(".", "_").humanize attr_name = @base.class.human_attribute_name(attribute, default: attr_name) I18n.t(:"errors.format", default: "%{attribute} %{message}", attribute: attr_name, message: message) end
def full_messages
person.errors.full_messages
person = Person.create(address: '123 First St.')
end
validates_length_of :name, in: 5..30
validates_presence_of :name, :address, :email
class Person
Returns all the full error messages in an array.
def full_messages map { |attribute, message| full_message(attribute, message) } end
def full_messages_for(attribute)
person.errors.full_messages_for(:name)
person = Person.create()
end
validates_length_of :name, in: 5..30
validates_presence_of :name, :email
class Person
Returns all the full error messages for a given attribute in an array.
def full_messages_for(attribute) attribute = attribute.to_sym messages[attribute].map { |message| full_message(attribute, message) } end
def generate_message(attribute, type = :invalid, options = {})
* errors.attributes.title.blank
* activemodel.errors.messages.blank
* any default you provided through the +options+ hash (in the activemodel.errors scope)
* activemodel.errors.models.user.blank
* activemodel.errors.models.user.attributes.title.blank
* activemodel.errors.models.admin.blank
* activemodel.errors.models.admin.attributes.title.blank
it looks for these translations:
the :blank error message for the title attribute,
class Admin < User; end and you wanted the translation for
models too, but only if the model itself hasn't been found. Say you have
When using inheritance in your models, it will check all the inherited
interpolation.
name, translated attribute name and the value are available for
(e.g. activemodel.errors.messages.MESSAGE). The translated model
that is not there also, it returns the translation of the default message
if it's not there, it's looked up in activemodel.errors.models.MODEL.MESSAGE and if
Error messages are first looked up in activemodel.errors.models.MODEL.attributes.ATTRIBUTE.MESSAGE,
(activemodel.errors.messages).
Translates an error message in its default scope
def generate_message(attribute, type = :invalid, options = {}) type = options.delete(:message) if options[:message].is_a?(Symbol) if @base.class.respond_to?(:i18n_scope) defaults = @base.class.lookup_ancestors.map do |klass| [ :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.#{type}", :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.#{type}" ] end else defaults = [] end defaults << :"#{@base.class.i18n_scope}.errors.messages.#{type}" if @base.class.respond_to?(:i18n_scope) defaults << :"errors.attributes.#{attribute}.#{type}" defaults << :"errors.messages.#{type}" defaults.compact! defaults.flatten! key = defaults.shift defaults = options.delete(:message) if options[:message] value = (attribute != :base ? @base.send(:read_attribute_for_validation, attribute) : nil) options = { default: defaults, model: @base.model_name.human, attribute: @base.class.human_attribute_name(attribute), value: value, object: @base }.merge!(options) I18n.translate(key, options) end
def include?(attribute)
person.errors.include?(:name) # => true
person.errors.messages # => {:name=>["cannot be nil"]}
+attribute+, +false+ otherwise.
Returns +true+ if the error messages include an error for the given key
def include?(attribute) attribute = attribute.to_sym messages.key?(attribute) && messages[attribute].present? end
def init_with(coder) # :nodoc:
def init_with(coder) # :nodoc: coder.map.each { |k, v| instance_variable_set(:"@#{k}", v) } @details ||= {} apply_default_array(@messages) apply_default_array(@details) end
def initialize(base)
end
@errors = ActiveModel::Errors.new(self)
def initialize
class Person
Pass in the instance of the object that is using the errors object.
def initialize(base) @base = base @messages = apply_default_array({}) @details = apply_default_array({}) end
def initialize_dup(other) # :nodoc:
def initialize_dup(other) # :nodoc: @messages = other.messages.dup @details = other.details.deep_dup super end
def keys
person.errors.messages # => {:name=>["cannot be nil", "must be specified"]}
Returns all message keys.
def keys messages.keys end
def marshal_dump # :nodoc:
def marshal_dump # :nodoc: [@base, without_default_proc(@messages), without_default_proc(@details)] end
def marshal_load(array) # :nodoc:
def marshal_load(array) # :nodoc: @base, @messages, @details = array apply_default_array(@messages) apply_default_array(@details) end
def normalize_detail(message, options)
def normalize_detail(message, options) { error: message }.merge(options.except(*CALLBACKS_OPTIONS + MESSAGE_OPTIONS)) end
def normalize_message(attribute, message, options)
def normalize_message(attribute, message, options) case message when Symbol generate_message(attribute, message, options.except(*CALLBACKS_OPTIONS)) else message end end
def size
person.errors.add(:name, :not_specified, message: "must be specified")
person.errors.size # => 1
person.errors.add(:name, :blank, message: "can't be blank")
Returns the number of error messages.
def size values.flatten.size end
def to_hash(full_messages = false)
person.errors.to_hash # => {:name=>["cannot be nil"]}
is +true+, it will contain full messages (see +full_message+).
Returns a Hash of attributes with their error messages. If +full_messages+
def to_hash(full_messages = false) if full_messages messages.each_with_object({}) do |(attribute, array), messages| messages[attribute] = array.map { |message| full_message(attribute, message) } end else without_default_proc(messages) end end
def to_xml(options = {})
#
#
#
#
# =>
person.errors.to_xml
person.errors.add(:name, :not_specified, message: "must be specified")
person.errors.add(:name, :blank, message: "can't be blank")
Returns an xml formatted representation of the Errors hash.
def to_xml(options = {}) to_a.to_xml({ root: "errors", skip_types: true }.merge!(options)) end
def values
person.errors.messages # => {:name=>["cannot be nil", "must be specified"]}
Returns all message values.
def values messages.values end
def without_default_proc(hash)
def without_default_proc(hash) hash.dup.tap do |new_h| new_h.default_proc = nil end end