Skip to content

Commit

Permalink
UniquenessValidator exclude itself when PK changed
Browse files Browse the repository at this point in the history
When changing the PK for a record which has a uniqueness validation on
some other attribute, Active Record should exclude itself from the
validation based on the PK value stored on the DB (id_was) instead of
its new value (id).
  • Loading branch information
diego-silva committed Feb 9, 2016
1 parent b5eb242 commit f1daa2b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/validations/uniqueness.rb
Expand Up @@ -19,7 +19,7 @@ def validate_each(record, attribute, value)
relation = build_relation(finder_class, table, attribute, value)
if record.persisted? && finder_class.primary_key.to_s != attribute.to_s
if finder_class.primary_key
relation = relation.where.not(finder_class.primary_key => record.id)
relation = relation.where.not(finder_class.primary_key => record.id_was)
else
raise UnknownPrimaryKey.new(finder_class, "Can not validate uniqueness for persisted record without primary key.")
end
Expand Down
11 changes: 11 additions & 0 deletions activerecord/test/cases/validations/uniqueness_validation_test.rb
Expand Up @@ -469,4 +469,15 @@ def self.name; "Dashboard" end
assert_match(/\AUnknown primary key for table dashboards in model/, e.message)
assert_match(/Can not validate uniqueness for persisted record without primary key.\z/, e.message)
end

def test_validate_uniqueness_ignores_itself_when_primary_key_changed
Topic.validates_uniqueness_of(:title)

t = Topic.new("title" => "This is a unique title")
assert t.save, "Should save t as unique"

t.id += 1
assert t.valid?, "Should be valid"
assert t.save, "Should still save t as unique"
end
end

0 comments on commit f1daa2b

Please sign in to comment.