Class: ActiveRecord::Validations::UniquenessValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::Validator
- ActiveModel::EachValidator
- ActiveRecord::Validations::UniquenessValidator
- Defined in:
- activerecord/lib/active_record/validations/uniqueness.rb
Instance Attribute Summary
Attributes inherited from ActiveModel::EachValidator
Attributes inherited from ActiveModel::Validator
Instance Method Summary collapse
-
#initialize(options) ⇒ UniquenessValidator
constructor
A new instance of UniquenessValidator.
-
#setup(klass) ⇒ Object
Unfortunately, we have to tie Uniqueness validators to a class.
- #validate_each(record, attribute, value) ⇒ Object
Methods inherited from ActiveModel::EachValidator
Methods inherited from ActiveModel::Validator
Constructor Details
#initialize(options) ⇒ UniquenessValidator
Returns a new instance of UniquenessValidator.
6 7 8 |
# File 'activerecord/lib/active_record/validations/uniqueness.rb', line 6 def initialize() super(.reverse_merge(:case_sensitive => true)) end |
Instance Method Details
#setup(klass) ⇒ Object
Unfortunately, we have to tie Uniqueness validators to a class.
11 12 13 |
# File 'activerecord/lib/active_record/validations/uniqueness.rb', line 11 def setup(klass) @klass = klass end |
#validate_each(record, attribute, value) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'activerecord/lib/active_record/validations/uniqueness.rb', line 15 def validate_each(record, attribute, value) finder_class = find_finder_class_for(record) table = finder_class.arel_table coder = record.class.serialized_attributes[attribute.to_s] if value && coder value = coder.dump value end relation = build_relation(finder_class, table, attribute, value) relation = relation.and(table[finder_class.primary_key.to_sym].not_eq(record.send(:id))) if record.persisted? Array.wrap([:scope]).each do |scope_item| scope_value = record.send(scope_item) relation = relation.and(table[scope_item].eq(scope_value)) end if finder_class.unscoped.where(relation).exists? record.errors.add(attribute, :taken, .except(:case_sensitive, :scope).merge(:value => value)) end end |