Class: Volt::UniqueValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/volt/models/validators/unique_validator.rb

Class Method Summary collapse

Class Method Details

.validate(model, field_name, args) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/volt/models/validators/unique_validator.rb', line 3

def self.validate(model, field_name, args)
  if RUBY_PLATFORM != 'opal'
    if args
      value  = model.get(field_name)

      query = {}
      # Check to see if any other documents have this value.
      query[field_name.to_s] = value
      query['id'] = { '$ne' => model.id }

      # Check if the value is taken
      # TODO: need a way to handle scope for unique
      return Volt.current_app.store.get(model.path[-2]).where(query).first.then do |item|
        if item
          message = (args.is_a?(Hash) && args[:message]) || 'is already taken'

          # return the error
          next { field_name => [message] }
        end
      end
    end
  end

  # no errors
  {}
end