]> git.openstreetmap.org Git - rails.git/blob - app/validators/normalized_uniqueness_validator.rb
Merge pull request #5932 from tomhughes/frozen-strings
[rails.git] / app / validators / normalized_uniqueness_validator.rb
1 # frozen_string_literal: true
2
3 class NormalizedUniquenessValidator < ActiveModel::EachValidator
4   def validate_each(record, attribute, value)
5     relation = if options.fetch(:case_sensitive, true)
6                  record.class.where("NORMALIZE(#{attribute}, NFKC) = NORMALIZE(?, NFKC)", value)
7                else
8                  record.class.where("LOWER(NORMALIZE(#{attribute}, NFKC)) = LOWER(NORMALIZE(?, NFKC))", value)
9                end
10
11     relation = relation.where.not(record.class.primary_key => [record.id_in_database]) if record.persisted?
12
13     if relation.exists?
14       error_options = options.except(:case_sensitive)
15       error_options[:value] = value
16
17       record.errors.add(attribute, :taken, **error_options)
18     end
19   end
20 end