[英]Rails uniqueness validation does not seem to be working
我在下面有针对我的产品模型的验证规则,并且在测试规则时,我发现:title的唯一性:true实际上没有任何作用。
validates( :title, presence: {message: ' must be given'}, uniqueness: true )
举例来说,如果我建立两个标题相同的执行个体,
a = Product.new title: 'title', description: 'hello!!', user: User.find(39)
a.save
id | title | description | price | created_at | updated_at | user_id |
+-----+-------+-------------+-------+--------------------+-------------+
162 | title | hello!! | 0.0 | 2018-... | 2018-02... | 39 |
b = Product.new title: 'title', description: 'hahah', user: User.find(39)
b.save
id | title | description | price | created_at | updated_at | user_id |
+-----+-------+-------------+-------+--------------------+-------------+
163 | title | hahah | 0.0 | 2018-... | 2018-02-2... | 39 |
我不明白为什么唯一性根本不起作用?
将代码添加到项目中的任何文件后,尝试重新启动服务器或重新加载控制台。
在100%事件中不信任唯一性验证。 为确保某些字段唯一,请在数据库中添加唯一索引。 这是由uniq验证在保存之前检查属性的值是否唯一引起的,因此,如果两个不同的数据库连接创建具有相同值的两个记录,则不会引发错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.