Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix uniqueness validation with an after_create hook. #23887

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/validations/uniqueness.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def validate_each(record, attribute, value)
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
Expand Down
18 changes: 18 additions & 0 deletions activerecord/test/cases/validations/uniqueness_validation_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@ class CoolTopic < Topic
validates_uniqueness_of :id
end

class TopicWithAfterCreate < Topic
after_create :set_author

def set_author
update_attributes!(:author_name => "#{title} #{id}")
end
end

class UniquenessValidationTest < ActiveRecord::TestCase
INT_MAX_VALUE = 2147483647

Expand Down Expand Up @@ -469,6 +477,16 @@ def test_validate_uniqueness_ignores_itself_when_primary_key_changed
assert t.save, "Should still save t as unique"
end

def test_validate_uniqueness_with_after_create_performing_save
TopicWithAfterCreate.validates_uniqueness_of(:title)
topic = TopicWithAfterCreate.create!(:title => "Title1")
assert topic.author_name.start_with?("Title1")

topic2 = TopicWithAfterCreate.new(:title => "Title1")
refute topic2.valid?
assert_equal(["has already been taken"], topic2.errors[:title])
end

def test_validate_uniqueness_uuid
skip unless current_adapter?(:PostgreSQLAdapter)
item = UuidItem.create!(uuid: SecureRandom.uuid, title: 'item1')
Expand Down