Sha256: 9c4fdfdd0b95c12905eca94d37dbab7f52b154e9bd5b599d0ccb070f235a8251

Contents?: true

Size: 1.38 KB

Versions: 17

Compression:

Stored size: 1.38 KB

Contents

# frozen_string_literal: true

# Validation error class to wrap association records' errors,
# with index_errors support.
module ActiveRecord
  module Associations
    class NestedError < ::ActiveModel::NestedError
      def initialize(association, inner_error)
        @base = association.owner
        @association = association
        @inner_error = inner_error
        super(@base, inner_error, { attribute: compute_attribute(inner_error) })
      end

      private
        attr_reader :association

        def compute_attribute(inner_error)
          association_name = association.reflection.name

          if association.collection? && index_errors_setting && index
            "#{association_name}[#{index}].#{inner_error.attribute}".to_sym
          else
            "#{association_name}.#{inner_error.attribute}".to_sym
          end
        end

        def index_errors_setting
          @index_errors_setting ||=
            association.options.fetch(:index_errors, ActiveRecord.index_nested_attribute_errors)
        end

        def index
          @index ||= ordered_records&.find_index(inner_error.base)
        end

        def ordered_records
          case index_errors_setting
          when true # default is association order
            association.target
          when :nested_attributes_order
            association.nested_attributes_target
          end
        end
    end
  end
end

Version data entries

17 entries across 17 versions & 2 rubygems

Version Path
activerecord-8.0.0 lib/active_record/associations/nested_error.rb
activerecord-7.2.2 lib/active_record/associations/nested_error.rb
activerecord-8.0.0.rc2 lib/active_record/associations/nested_error.rb
activerecord-7.2.1.2 lib/active_record/associations/nested_error.rb
activerecord-8.0.0.rc1 lib/active_record/associations/nested_error.rb
activerecord-7.2.1.1 lib/active_record/associations/nested_error.rb
activerecord-8.0.0.beta1 lib/active_record/associations/nested_error.rb
omg-activerecord-8.0.0.alpha9 lib/active_record/associations/nested_error.rb
omg-activerecord-8.0.0.alpha8 lib/active_record/associations/nested_error.rb
omg-activerecord-8.0.0.alpha7 lib/active_record/associations/nested_error.rb
omg-activerecord-8.0.0.alpha4 lib/active_record/associations/nested_error.rb
omg-activerecord-8.0.0.alpha3 lib/active_record/associations/nested_error.rb
omg-activerecord-8.0.0.alpha2 lib/active_record/associations/nested_error.rb
omg-activerecord-8.0.0.alpha1 lib/active_record/associations/nested_error.rb
activerecord-7.2.1 lib/active_record/associations/nested_error.rb
activerecord-7.2.0 lib/active_record/associations/nested_error.rb
activerecord-7.2.0.rc1 lib/active_record/associations/nested_error.rb