Sha256: c83e5fc4e76aecf5371982aee5b10b6095c86443ca38e309ab551b69c228ea39

Contents?: true

Size: 1.36 KB

Versions: 3

Compression:

Stored size: 1.36 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 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

3 entries across 3 versions & 1 rubygems

Version Path
activerecord-7.2.0.beta3 lib/active_record/associations/nested_error.rb
activerecord-7.2.0.beta2 lib/active_record/associations/nested_error.rb
activerecord-7.2.0.beta1 lib/active_record/associations/nested_error.rb