1 # frozen_string_literal: true
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)
8 record.class.where("LOWER(NORMALIZE(#{attribute}, NFKC)) = LOWER(NORMALIZE(?, NFKC))", value)
11 relation = relation.where.not(record.class.primary_key => [record.id_in_database]) if record.persisted?
14 error_options = options.except(:case_sensitive)
15 error_options[:value] = value
17 record.errors.add(attribute, :taken, **error_options)