Class: Uniqueable::UniqueableValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- Uniqueable::UniqueableValidator
- Defined in:
- lib/uniqueable/validates_uniqueable.rb
Instance Method Summary collapse
-
#initialize(options) ⇒ UniqueableValidator
constructor
A new instance of UniqueableValidator.
- #validate_each(record, attribute, value) ⇒ Object
Constructor Details
#initialize(options) ⇒ UniqueableValidator
Returns a new instance of UniqueableValidator.
3 4 5 |
# File 'lib/uniqueable/validates_uniqueable.rb', line 3 def initialize() super(.reverse_merge(:case_sensitive => true)) end |
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/uniqueable/validates_uniqueable.rb', line 7 def validate_each(record, attribute, value) checks = record.class.uniqueable_checks[[:group]] #TODO: Make the check atomic return unless checks checks.each do |klass, keys| keys.each do |key| #Check nothing exists with this pair conditions = [] if key.kind_of?(Hash) conditions = key[key.keys.first][:conditions] key = key.keys.first end if [:case_sensitive] result = klass.unscoped.where(["#{key} = ?", value]).where(conditions).all else value = value.downcase if value.kind_of?(String) result = klass.unscoped.where(["lower(#{key}) = ?", value]).where(conditions).all end unless result.empty? #Check that the result isn't the record we are validating unless result.first == record return record.errors.add(attribute, :taken) end end end end end |