Class: ActiveRecord::Validations::UniquenessValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- ActiveRecord::Validations::UniquenessValidator
- Defined in:
- lib/active_record/validations/uniqueness.rb
Overview
:nodoc:
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
Constructor Details
#initialize(options) ⇒ UniquenessValidator
Returns a new instance of UniquenessValidator.
4 5 6 7 8 9 10 |
# File 'lib/active_record/validations/uniqueness.rb', line 4 def initialize() if [:conditions] && ![:conditions].respond_to?(:call) raise ArgumentError, "#{[:conditions]} was passed as :conditions but is not callable. " \ "Pass a callable instead: `conditions: -> { where(approved: true) }`" end super({ case_sensitive: true }.merge!()) end |
Instance Method Details
#setup(klass) ⇒ Object
Unfortunately, we have to tie Uniqueness validators to a class.
13 14 15 |
# File 'lib/active_record/validations/uniqueness.rb', line 13 def setup(klass) @klass = klass end |
#validate_each(record, attribute, value) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/active_record/validations/uniqueness.rb', line 17 def validate_each(record, attribute, value) finder_class = find_finder_class_for(record) table = finder_class.arel_table value = deserialize_attribute(record, attribute, value) relation = build_relation(finder_class, table, attribute, value) relation = relation.and(table[finder_class.primary_key.to_sym].not_eq(record.id)) if record.persisted? relation = scope_relation(record, table, relation) relation = finder_class.unscoped.where(relation) relation = relation.merge([:conditions]) if [:conditions] if relation.exists? = .except(:case_sensitive, :scope, :conditions) [:value] = value record.errors.add(attribute, :taken, ) end end |