Class: Mobility::ActiveRecord::UniquenessValidator

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

Overview

Note:

This validator does not support case sensitivity, since doing so would significantly complicate implementation.

A backend-agnostic uniqueness validator for ActiveRecord translated attributes. To use the validator, you must extend Mobility before calling validates (see example below).

Examples:

Validating uniqueness on translated model

class Post < ActiveRecord::Base
  extend Mobility
  translates :title

  # This must come *after* extending Mobility.
  validates :title, uniqueness: true
end

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/active_record/uniqueness_validator.rb', line 25

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

  if (([*options[:scope]] + [attribute]).map(&:to_s) & klass.mobility_attributes).present?
    return unless value.present?
    relation = klass.unscoped.__mobility_query_scope__ 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