Sha256: 4a1337a69c479cd5c8224c63ed39b18afe081540de016da6fb47af83d8e7b1de

Contents?: true

Size: 1.4 KB

Versions: 7

Compression:

Stored size: 1.4 KB

Contents

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

        table_name   = record.class.quoted_table_name

        if value && record.class.serialized_attributes.key?(attribute.to_s)
          value = YAML.dump value
        end

        sql, params  = mount_sql_and_params(finder_class, table_name, attribute, value)

        relation = table.where(sql, *params)

        Array.wrap(options[:scope]).each do |scope_item|
          scope_value = record.send(scope_item)
          relation = relation.where(scope_item => scope_value)
        end

        if record.persisted?
          # CPK
          if record.composite?
            predicate = nil
            record.ids_hash.each do |key, value|
              neq = relation.table[key].not_eq(value)
              predicate = predicate ? predicate.and(neq) : neq
            end
            relation = relation.where(predicate)
          else
            # TODO : This should be in Arel
            relation = relation.where("#{record.class.quoted_table_name}.#{record.class.primary_key} <> ?", record.send(:id))
          end
        end

        if relation.exists?
          record.errors.add(attribute, :taken, options.except(:case_sensitive, :scope).merge(:value => value))
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
composite_primary_keys-3.1.5 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-3.1.4 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-3.1.2 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-3.1.1 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-3.1.0 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-3.0.9 lib/composite_primary_keys/validations/uniqueness.rb
composite_primary_keys-3.0.8 lib/composite_primary_keys/validations/uniqueness.rb