Class: ActiveItem::AssociatedValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/active_item/validations.rb

Overview

ActiveModel validator that checks associated records are valid. Validates in-memory built records (via .build) and already-loaded records. Does not trigger a DB query — only checks what's already in memory.

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, _value) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/active_item/validations.rb', line 75

def validate_each(record, attribute, _value)
  association_config = record.class._associations[attribute]
  return unless association_config

  associated = record.send(attribute)

  # Only validate loaded/cached records — don't trigger a DB query
  records = if associated.respond_to?(:loaded?) && associated.loaded?
              associated.to_a
            else
              []
            end

  records.each do |child|
    next if child.valid?

    record.errors.add(attribute, :invalid, **options.except(:on))
    break
  end
end