Class: Babylonia::Rails::Validators::LocaleUniquenessValidator

Inherits:
ActiveRecord::Validations::UniquenessValidator
  • Object
show all
Defined in:
lib/babylonia/rails/validators/uniqueness_validator.rb

Instance Method Summary collapse

Instance Method Details

#validate(record) ⇒ Object



8
9
10
11
12
13
14
# File 'lib/babylonia/rails/validators/uniqueness_validator.rb', line 8

def validate(record)
  (ActiveRecord::VERSION::MAJOR > 3 ? attributes : attributes.first).each do |locale, attribute|
    value = record.read_attribute_for_validation(:"#{attribute}_#{locale}")
    next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
    validate_each(record, attribute, locale, value)
  end
end

#validate_each(record, attribute, locale, value) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/babylonia/rails/validators/uniqueness_validator.rb', line 16

def validate_each(record, attribute, locale, value)
  finder_class = find_finder_class_for(record)
  table = finder_class.arel_table

  relation = build_relation(finder_class, table, attribute, locale, value)
  relation = relation.and(table[finder_class.primary_key.to_sym].not_eq(record.id)) if record.persisted?
  if ActiveRecord::VERSION::MAJOR > 3
    relation = scope_relation(record, table, relation)
  else
    Array.wrap(options[:scope]).each do |scope_item|
      scope_value = record.read_attribute(scope_item)
      relation = relation.and(table[scope_item].eq(scope_value))
    end
  end
  relation = finder_class.unscoped.where(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}_#{locale}", :taken, error_options)
  end
end