UniquenessValidator exclude itself when PK changed
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).
This commit is contained in:
parent
b5eb2423b6
commit
f1daa2be52
@ -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
|
||||
|
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user