Class: ActiveModel::Validations::GrandparentValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/can_has_validations/validators/grandparent_validator.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, association) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/can_has_validations/validators/grandparent_validator.rb', line 9

def validate_each(record, attribute, association)
  # to allow attribute to be the _id and not just the actual association
  if attribute.to_s.ends_with?('_id')
    association = record.send(attribute.to_s.sub(/_id$/,''))
  end
  all_match = Array(options[:scope]).all? do |scope|
    cousin = record.send(scope)
    if cousin.nil?
      options[:allow_nil]
    else
      association &&
        association.send(options[:parent]) == cousin.send(options[:parent])
    end
  end
  unless all_match
    record.errors.add(attribute, :invalid, **options.except(:allow_nil, :parent, :scope))
  end
end