class Errors
Ruby on Rails 7.2.3
Active Model Errors
Provides error related functionalities you can include in your object for handling error messages and interacting with Action View helpers.
A minimal implementation could be:
class Person
# Required dependency for ActiveModel::Errors
extend ActiveModel::Naming
def initialize
@errors = ActiveModel::Errors.new(self)
end
attr_accessor :name
attr_reader :errors
def validate!
errors.add(:name, :blank, message: "cannot be nil") if name.nil?
end
# The following methods are needed to be minimally implemented
def read_attribute_for_validation(attr)
send(attr)
end
def self.human_attribute_name(attr, options = {})
attr
end
def self.lookup_ancestors
[self]
end
end
The last three methods are required in your object for Errors to be able to generate error messages correctly and also handle multiple languages. Of course, if you extend your object with ActiveModel::Translation you will not need to implement the last two. Likewise, using ActiveModel::Validations will handle the validation related methods for you.
The above allows you to do:
person = Person.new
person.validate! # => ["cannot be nil"]
person.errors.full_messages # => ["name cannot be nil"]
# etc..
Inherits from
Includes
Extends
Constants
Attributes
Methods (defined here)
- # []
- # add
- # added?
- # as_json
- # attribute_names
- # clear
- # delete
- # details
- # each
- # empty?
- # full_message
- # full_messages
- # full_messages_for
- # generate_message
- # group_by_attribute
- # has_key?
- # import
- # include?
- # key?
- # merge!
- # messages
- # messages_for
- # of_kind?
- # size
- # to_a
- # to_hash
- # where
- self. new
Private methods (1)
Show private methods Implementation detail — not part of the public API.
Methods (inherited)
From Enumerable
(14)
- # compact_blank
- # exclude?
- # excluding
- # in_order_of
- # including
- # index_by
- # index_with
- # many?
- # maximum
- # minimum
- # pick
- # pluck
- # sole
- # without
From Object
(17)
- # acts_like?
- # blank?
- # deep_dup
- # duplicable?
- # html_safe?
- # in?
- # instance_values
- # instance_variable_names
- # presence
- # presence_in
- # present?
- # to_param
- # to_query
- # try
- # try!
- # with
- # with_options
From ActiveSupport::NumericWithFormat
(2)
- # to_formatted_s
- # to_fs