Rails 唯一性验证似乎不起作用
Rails uniqueness validation does not seem to be working
我的产品模型有以下验证规则,在测试规则时,我发现 uniqueness: true for :title 实际上没有任何作用。
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 验证会在保存之前检查属性的值是否唯一,因此如果两个不同的数据库连接创建两个具有相同值的记录,则不会引发错误。
我的产品模型有以下验证规则,在测试规则时,我发现 uniqueness: true for :title 实际上没有任何作用。
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 验证会在保存之前检查属性的值是否唯一,因此如果两个不同的数据库连接创建两个具有相同值的记录,则不会引发错误。