Sha256: b166b4e898eaf2e6b98a8d6ad123971dbb6b0ca6c3b6ddd2e15b3e9e79de682d

Contents?: true

Size: 1.28 KB

Versions: 14

Compression:

Stored size: 1.28 KB

Contents

module ActiveRecord
  module Validations
    class UniquenessValidator
      def validate_each(record, attribute, value)
        finder_class = find_finder_class_for(record)
        value = map_enum_attribute(finder_class, attribute, value)

        relation = build_relation(finder_class, attribute, value)
        if record.persisted?
          # CPK
          if finder_class.primary_key.is_a?(Array)
            predicate = finder_class.cpk_id_predicate(finder_class.arel_table, finder_class.primary_key, record.id_in_database || record.id)
            relation = relation.where.not(predicate)
          elsif finder_class.primary_key
            relation = relation.where.not(finder_class.primary_key => record.id_in_database)
          else
            raise UnknownPrimaryKey.new(finder_class, "Can not validate uniqueness for persisted record without primary key.")
          end
        end
        relation = scope_relation(record, relation)
        relation = relation.merge(options[:conditions]) if options[:conditions]

        if relation.exists?
          error_options = options.except(:case_sensitive, :scope, :conditions)
          error_options[:value] = value

          record.errors.add(attribute, :taken, **error_options)
        end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
composite_primary_keys-13.0.7 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-13.0.6 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-13.0.5 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-13.0.4 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-13.0.1 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-13.0.0 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-12.0.10 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-12.0.9 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-12.0.8 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-12.0.6 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-12.0.5 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-12.0.4 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-12.0.3 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-12.0.2 lib/composite_primary_keys/validations/uniqueness.rb