class ActiveModel::Validations::GrandparentValidator

Public Instance Methods

validate_each(record, attribute, association) click to toggle source
# 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