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