Class: Spira::Validations::UniquenessValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/spira/validations/uniqueness.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ UniquenessValidator

Returns a new instance of UniquenessValidator


13
14
15
16
# File 'lib/spira/validations/uniqueness.rb', line 13

def initialize(options)
  super
  @klass = options.fetch(:class)
end

Instance Method Details

#setup(klass) ⇒ Object


9
10
11
# File 'lib/spira/validations/uniqueness.rb', line 9

def setup(klass)
  @klass = klass
end

#validate_each(record, attribute, value) ⇒ Object


19
20
21
22
23
24
25
26
# File 'lib/spira/validations/uniqueness.rb', line 19

def validate_each(record, attribute, value)
  @klass.find_each(:conditions => {attribute => value}) do |other_record|
    if other_record.subject != record.subject
      record.errors.add(attribute, "is already taken")
      break
    end
  end
end