Class: DatastaxRails::Validations::UniquenessValidator

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

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ UniquenessValidator

Returns a new instance of UniquenessValidator.



6
7
8
# File 'lib/datastax_rails/validations/uniqueness.rb', line 6

def initialize(options)
  super
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/datastax_rails/validations/uniqueness.rb', line 10

def validate_each(record, attribute, value)
  return true if options[:allow_blank] && value.blank?
  # XXX: The following will break if/when abstract base classes
  #      are implemented in datastax_rails (such as STI)
  finder_class = record.class

  scope = finder_class.where(attribute => value)
  scope = scope.where_not(id: record.id) if record.persisted?

  Array.wrap(options[:scope]).each do |scope_item|
    scope_value = record.send(scope_item)
    scope_value = nil if scope_value.blank?
    scope = scope.where(scope_item => scope_value)
  end

  if scope.exists? # rubocop:disable Style/GuardClause
    message = options[:message] || 'has already been taken'
    record.errors.add(attribute, message, options.except(:case_sensitive, :scope).merge(value: value))
  end
end