Sha256: 2a4979df1fffa0616c90265cbe68b4905503ad688c3e96019f364ad334918b83

Contents?: true

Size: 1.17 KB

Versions: 17

Compression:

Stored size: 1.17 KB

Contents

module Mobility
  module ActiveRecord
    class UniquenessValidator < ::ActiveRecord::Validations::UniquenessValidator
      def validate_each(record, attribute, value)
        klass = record.class

        if ((Array(options[:scope]) + [attribute]).map(&:to_s) & klass.translated_attribute_names).present?
          return unless value.present?
          relation = klass.send(Mobility.query_method).where(attribute => value)
          relation = relation.where.not(klass.primary_key => record.id) if record.persisted?
          relation = mobility_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
        else
          super
        end
      end

      private

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

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
mobility-0.3.6 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.3.5 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.3.4 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.3.3 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.3.2 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.3.1 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.3.0 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.2.3 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.2.2 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.2.1 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.2.0 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.1.20 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.1.19 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.1.18 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.1.17 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.1.16 lib/mobility/active_record/uniqueness_validator.rb
mobility-0.1.15 lib/mobility/active_record/uniqueness_validator.rb