Class: WhyValidationsSuckIn96::ValidatesUniqueness

Inherits:
WhyValidationsSuckIn96::Validation show all
Includes:
WhyValidationsSuckIn96::AttributeBasedValidation, WhyValidationsSuckIn96::SkippableValidation
Defined in:
lib/whyvalidationssuckin96/rails/macros/validates_uniqueness.rb

Overview

Checks to see if a given attribute is present in any other records in the databaser

Examples:

Default usage

  setup_validations do
    validates_uniqueness_of :name
  end

Check in a case sensitive fashion

  setup_validations do
    validates_uniqueness_of :name, :case_sensitive => true
  end

Scope uniqueness to another attribute

  setup_validations do
    validates_uniqueness_of :name, :scope => :account_id
  end

Scope uniqueness to multiple other attributes

  setup_validations do
    validates_uniqueness_of :name, :scope => [:account_id, :domain]
  end

When used with STI, check only uniqueness of records of the current type

  setup_validations do
    validates_uniqueness_of :name, :base_class_scope => false
  end

Constant Summary

DefaultOptions =
{:message => "has already been taken", :case_sensitive => false, :base_class_scope => true}

Constants inherited from WhyValidationsSuckIn96::Validation

DefaultOptions

Instance Method Summary

Methods included from WhyValidationsSuckIn96::AttributeBasedValidation

#attribute, #attribute_value, #initialize

Methods inherited from WhyValidationsSuckIn96::Validation

#failed?, #has_run?, #initialize, #message, new_subclass, #passed?, #validates?

Constructor Details

This class inherits a constructor from WhyValidationsSuckIn96::AttributeBasedValidation

Instance Method Details

- (Object) validate



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/whyvalidationssuckin96/rails/macros/validates_uniqueness.rb', line 38

def validate
  super
  results = find_results
  result_ids = results.collect { |r| r[scope_primary_key] }
  if results.empty? || result_ids.include?(validatable[scope_primary_key])
    pass
  elsif !results.empty? && options[:case_sensitive]
    (results.any? { |r| r[attribute].to_s == attribute_value.to_s }) ? fail : pass
  else
    fail
  end
end