问题描述
当有多个进程时,在Rails中使用唯一性验证是不安全的,除非在数据库上也强制执行约束(在我的情况下是PostgreSQL数据库,所以请参阅)。
Using uniqueness validations in Rails is not safe when there are multiple processes unless the constraint is also enforced on the database (in my case a PostgreSQL database so see http://robots.thoughtbot.com/the-perils-of-uniqueness-validations).
在我的情况下,唯一性验证是有条件的:只有在模型中的另一个属性变为true时才应强制执行。所以我有
In my case, the uniqueness validation is conditional: it should only be enforced if another attribute in the model becomes true. So I have
class Model < ActiveRecord::Base
validates_uniqueness_of :text, if: :is_published?
def is_published?
self.is_published
end
end
所以模型有两个属性: is_published
(布尔值)和文本
(文本属性)。 text
在所有类型 Model
iff is_published
是真的。
So the model has two attributes: is_published
(a boolean) and text
(a text attribute). text
should be unique across all models of type Model
iff is_published
is true.
使用过于拘束,因为无论的值如何,它都会强制执行约束is_published
。
Using a unique index as suggested in http://robots.thoughtbot.com/the-perils-of-uniqueness-validations is too constraining because it would enforce the constraint regardless of the value of is_published
.
是否有人知道PostgreSQL数据库中的条件索引?还是另一种解决方法?
Is anyone aware of a "conditional" index on a PostgreSQL database? Or another way to fix this?
推荐答案
是的,使用。
CREATE UNIQUE INDEX tbl_txt_is_published_idx ON tbl (text) WHERE is_published;
示例:
这篇关于验证有条件时,数据库中的唯一性验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!