Class: NotNaughty::UniquenessValidation

Inherits:
Validation
  • Object
show all
Defined in:
lib/validations/uniqueness_validation.rb

Overview

Validates only if the fields in the model (specified by atts) are unique in the database. You should also add a unique index in the database, as this suffers from a fairly obvious race condition.

Possible Options:

:in

scope could be a single or multiple attributes

:message

see NotNaughty::Errors for details

:if

see NotNaughty::Validation::Condition for details

:unless

see NotNaughty::Validation::Condition for details

Instance Method Summary collapse

Constructor Details

#initialize(valid, attributes) ⇒ UniquenessValidation

:nodoc:



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/validations/uniqueness_validation.rb', line 14

def initialize(valid, attributes) #:nodoc:
  valid[:message] ||= '%s is already taken.'
  valid[:in] = case valid[:in]
  when Array; valid[:in].map { |scp| scp.to_sym }
  when String, String; [ valid[:in].to_sym ]
  else
    []
  end

  if valid[:allow_blank] or valid[:allow_nil]
    valid[:allow] = valid[:allow_blank] ? :blank? : :nil?

    super valid, attributes do |obj, attr, value|
      scope_values = obj.values.values_at(*valid[:in])
      scope = Hash[*valid[:in].zip(scope_values).flatten]

      value.send valid[:allow] or
      obj.model.find(scope.merge(attr => value)).nil? or
      obj.errors.add attr, valid[:message]
    end
  else

    super valid, attributes do |obj, attr, value|
      scope_values = obj.values.values_at(*valid[:in])
      scope = Hash[*valid[:in].zip(scope_values).flatten]

      obj.model.find(scope.merge(attr => value)).nil? or
      obj.errors.add attr, valid[:message]
    end
  end
end