Class: SafeUniquenessValidator

Inherits:
ActiveRecord::Validations::UniquenessValidator
  • Object
show all
Defined in:
lib/can_has_validations/validators/safe_uniqueness_validator.rb

Overview

better behaved version of the uniqueness validator

Difference is it doesn't puke if the foreign_key is an invalid type (for
example, an invalid string being provided for UUID type key). Instead,
returns an error about being unable to find the key value.

eg: validates :user_id, :safe_uniqueness=>true

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



8
9
10
11
12
13
14
# File 'lib/can_has_validations/validators/safe_uniqueness_validator.rb', line 8

def validate_each(record, attribute, value)
  record.transaction(:requires_new=>true) do
    super
  end
rescue ActiveRecord::StatementInvalid
  record.errors.add(attribute, "%{attribute} %{value} not found", options.except(:case_sensitive, :scope).merge(:value=>value))
end