From 0379da6abced76835368e7db5fe853571b055391 Mon Sep 17 00:00:00 2001 From: Joe Rafaniello Date: Thu, 25 Feb 2016 09:52:36 -0500 Subject: Fix uniqueness validation with an after_create hook. record.id_was is nil in after_create/after_save, so we should use id in these cases. While this logic feels incomplete, the existing update_record uses the same logic: https://github.com/rails/rails/blob/2fda4e0874a97a76107ab9e88305169f2c625933/activerecord/lib/active_record/relation.rb#L83 This logic was originally added for a similar problem: updates not working with after_create hook. See: 482f8c15b1d699c95bfbc3d836f674a09c0d9031 Followup to #23581 Fixes #23844 --- activerecord/lib/active_record/validations/uniqueness.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/lib/active_record/validations') diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb index 13053beb78..4a80cda0b8 100644 --- a/activerecord/lib/active_record/validations/uniqueness.rb +++ b/activerecord/lib/active_record/validations/uniqueness.rb @@ -18,7 +18,7 @@ module ActiveRecord relation = build_relation(finder_class, table, attribute, value) if record.persisted? if finder_class.primary_key - relation = relation.where.not(finder_class.primary_key => record.id_was) + relation = relation.where.not(finder_class.primary_key => record.id_was || record.id) else raise UnknownPrimaryKey.new(finder_class, "Can not validate uniqueness for persisted record without primary key.") end -- cgit v1.2.3