Class: Mobility::Plugins::ActiveRecord::UniquenessValidation::UniquenessValidator

Inherits:
ActiveRecord::Validations::UniquenessValidator
  • Object
show all
Defined in:
lib/mobility/plugins/active_record/uniqueness_validation.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

Parameters:

  • record (ActiveRecord::Base)

    Translated model

  • attribute (String)

    Name of attribute

  • value (Object)

    Attribute value



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/mobility/plugins/active_record/uniqueness_validation.rb', line 25

def validate_each(record, attribute, value)
  klass = record.class

  if ([*options[:scope]] + [attribute]).any? { |name| klass.mobility_attribute?(name) }
    return unless value.present?
    relation = Plugins::ActiveRecord::Query.build_query(klass.unscoped, Mobility.locale) do |m|
      node = m.__send__(attribute)
      options[:case_sensitive] == false ? node.lower.eq(value.downcase) : node.eq(value)
    end
    relation = relation.where.not(klass.primary_key => record.id) if record.persisted?
    relation = mobility_scope_relation(record, relation)
    relation = relation.merge(options[:conditions]) if options[:conditions]

    if relation.exists?
      error_options = options.except(:case_sensitive, :scope, :conditions)
      error_options[:value] = value

      record.errors.add(attribute, :taken, **error_options)
    end
  else
    super
  end
end