instance method each

Ruby on Rails 6.1.7.10

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

each(&block)

Iterates through each error object.

person.errors.add(:name, :too_short, count: 2)
person.errors.each do |error|
  # Will yield <#ActiveModel::Error attribute=name, type=too_short,
                                    options={:count=>3}>
end

To be backward compatible with past deprecated hash-like behavior, when block accepts two parameters instead of one, it iterates through each error key, value pair in the error messages hash. Yields the attribute and the error for that attribute. If the attribute has more than one error message, yields once for each error message.

person.errors.add(:name, :blank, message: "can't be blank")
person.errors.each do |attribute, message|
  # Will yield :name and "can't be blank"
end

person.errors.add(:name, :not_specified, message: "must be specified")
person.errors.each do |attribute, message|
  # Will yield :name and "can't be blank"
  # then yield :name and "must be specified"
end

Parameters

block block
Source
# File activemodel/lib/active_model/errors.rb, line 235
    def each(&block)
      if block.arity <= 1
        @errors.each(&block)
      else
        ActiveSupport::Deprecation.warn(<<~MSG)
          Enumerating ActiveModel::Errors as a hash has been deprecated.
          In Rails 6.1, `errors` is an array of Error objects,
          therefore it should be accessed by a block with a single block
          parameter like this:

          person.errors.each do |error|
            attribute = error.attribute
            message = error.message
          end

          You are passing a block expecting two parameters,
          so the old hash behavior is simulated. As this is deprecated,
          this will result in an ArgumentError in Rails 7.0.
        MSG
        @errors.
          sort { |a, b| a.attribute <=> b.attribute }.
          each { |error| yield error.attribute, error.message }
      end
    end

Defined in activemodel/lib/active_model/errors.rb line 235 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveModel::Errors

Type at least 2 characters to search.

↑↓ navigate · open · esc close