[英]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.