mysql中的唯一性校验,验证有条件时,数据库中的唯一性验证

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).

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

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.

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.

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值