class DatastaxRails::Validations::UniquenessValidator
Uniqueness validation
Public Class Methods
new(options)
click to toggle source
Calls superclass method
# File lib/datastax_rails/validations/uniqueness.rb, line 7 def initialize(options) super end
Public Instance Methods
validate_each(record, attribute, value)
click to toggle source
# File lib/datastax_rails/validations/uniqueness.rb, line 11 def validate_each(record, attribute, value) return true if options[:allow_blank] && value.blank? attr_to_check = options[:untokenized_attr] || attribute # XXX: I really want this error to show at load time, but I can't figure out how to find # the class from the above initializer. if record.column_for_attribute(attr_to_check) && record.column_for_attribute(attr_to_check).options['tokenized'] fail DatastaxRails::InvalidValidationError, "Cannot specify uniqueness on a tokenized field: #{attr_to_check}" end # 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(attr_to_check => 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