简体   繁体   English

Rails唯一性验证似乎不起作用

[英]Rails uniqueness validation does not seem to be working

I have this validation rules below for my product model, and while testing the rules, I found that the uniqueness: true for :title actually does nothing. 我在下面有针对我的产品模型的验证规则,并且在测试规则时,我发现:title的唯一性:true实际上没有任何作用。

  validates( :title, presence: {message: ' must be given'}, uniqueness: true )

For instance, if I create two instances with same title like so, 举例来说,如果我建立两个标题相同的执行个体,

 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     |

I don't understand why the uniqueness doesn't work at all ? 我不明白为什么唯一性根本不起作用?

  1. Try to restart a server or reload console after adding code to any file in the project. 将代码添加到项目中的任何文件后,尝试重新启动服务器或重新加载控制台。

  2. Uniqueness validation is not trusted in 100% events. 在100%事件中不信任唯一性验证。 TO be sure that some field is unique add a unique index in your database. 为确保某些字段唯一,请在数据库中添加唯一索引。 It's caused by that uniq validation checks that the attribute's value is unique just before save, so if two different database connections create two records with the same value it will not raise error. 这是由uniq验证在保存之前检查属性的值是否唯一引起的,因此,如果两个不同的数据库连接创建具有相同值的两个记录,则不会引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM