2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2013-05-23 12:52:12 +08:00
|
|
|
class UniqueAmongValidator < ActiveRecord::Validations::UniquenessValidator
|
|
|
|
def validate_each(record, attribute, value)
|
|
|
|
old_errors = record.errors[attribute].size
|
|
|
|
|
|
|
|
# look for any duplicates at all
|
|
|
|
super
|
|
|
|
|
|
|
|
new_errors = record.errors[attribute].size - old_errors
|
|
|
|
|
|
|
|
# do nothing further unless there were some duplicates.
|
|
|
|
unless new_errors == 0
|
|
|
|
# now look only in the collection we care about.
|
2020-06-18 23:19:47 +08:00
|
|
|
dupes = options[:collection].call(record).where("lower(#{attribute}) = ?", value.downcase)
|
2013-05-23 12:52:12 +08:00
|
|
|
dupes = dupes.where("id != ?", record.id) if record.persisted?
|
|
|
|
|
|
|
|
# pop off the error, if it was a false positive
|
|
|
|
record.errors[attribute].pop(new_errors) unless dupes.exists?
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|