Class: DatastaxRails::Validations::UniquenessValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- DatastaxRails::Validations::UniquenessValidator
- Defined in:
- lib/datastax_rails/validations/uniqueness.rb
Overview
Uniqueness validation
Instance Method Summary collapse
-
#initialize(options) ⇒ UniquenessValidator
constructor
A new instance of UniquenessValidator.
- #validate_each(record, attribute, value) ⇒ Object
Constructor Details
#initialize(options) ⇒ UniquenessValidator
Returns a new instance of UniquenessValidator.
7 8 9 |
# File 'lib/datastax_rails/validations/uniqueness.rb', line 7 def initialize() super end |
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
11 12 13 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 |
# File 'lib/datastax_rails/validations/uniqueness.rb', line 11 def validate_each(record, attribute, value) return true if [:allow_blank] && value.blank? attr_to_check = [: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).['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([: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] || 'has already been taken' record.errors.add(attribute, , .except(:case_sensitive, :scope).merge(value: value)) end end |