diff --git a/activerecord/lib/active_record/encryption/extended_deterministic_uniqueness_validator.rb b/activerecord/lib/active_record/encryption/extended_deterministic_uniqueness_validator.rb index 96d49fcd868..68265bd44c7 100644 --- a/activerecord/lib/active_record/encryption/extended_deterministic_uniqueness_validator.rb +++ b/activerecord/lib/active_record/encryption/extended_deterministic_uniqueness_validator.rb @@ -14,7 +14,7 @@ module ActiveRecord klass = record.class if klass.deterministic_encrypted_attributes&.include?(attribute) encrypted_type = klass.type_for_attribute(attribute) - [ encrypted_type, *encrypted_type.previous_types ].each do |type| + encrypted_type.previous_types.each do |type| encrypted_value = type.serialize(value) ActiveRecord::Encryption.without_encryption do super(record, attribute, encrypted_value) diff --git a/activerecord/test/cases/encryption/uniqueness_validations_test.rb b/activerecord/test/cases/encryption/uniqueness_validations_test.rb index f75d0832cfb..91f158e3baa 100644 --- a/activerecord/test/cases/encryption/uniqueness_validations_test.rb +++ b/activerecord/test/cases/encryption/uniqueness_validations_test.rb @@ -55,4 +55,11 @@ class ActiveRecord::Encryption::UniquenessValidationsTest < ActiveRecord::Encryp OldEncryptionBook.create! name: "DUNE" end end + + test "uniqueness validation does not revalidate the attribute with current encryption type" do + EncryptedBookWithUniquenessValidation.create!(name: "dune") + record = EncryptedBookWithUniquenessValidation.create(name: "dune") + + assert_equal record.errors.count, 1 + end end diff --git a/activerecord/test/models/book_encrypted.rb b/activerecord/test/models/book_encrypted.rb index ff335e10cfd..0c497137955 100644 --- a/activerecord/test/models/book_encrypted.rb +++ b/activerecord/test/models/book_encrypted.rb @@ -10,6 +10,13 @@ class EncryptedBook < ActiveRecord::Base encrypts :name, deterministic: true end +class EncryptedBookWithUniquenessValidation < ActiveRecord::Base + self.table_name = "encrypted_books" + + validates :name, uniqueness: true + encrypts :name, deterministic: true +end + class EncryptedBookWithDowncaseName < ActiveRecord::Base self.table_name = "encrypted_books"