【问题标题】:Rails uniqueness validation does not seem to be workingRails 唯一性验证似乎不起作用
【发布时间】:2018-07-30 19:55:55
【问题描述】:

我的产品模型在下面有这个验证规则,在测试规则时,我发现 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     |

我不明白为什么唯一性根本不起作用?

【问题讨论】:

  • 添加后是否尝试重新启动控制台/服务器?
  • 总是更喜欢数据库级别的唯一验证。应用程序中可能会出现引发条件,从而进一步产生重复记录。

标签: ruby-on-rails validation model validates-uniqueness-of


【解决方案1】:
  1. 将代码添加到项目中的任何文件后,尝试重新启动服务器或重新加载控制台。

  2. 唯一性验证在 100% 事件中不受信任。要确保某些字段是唯一的,请在数据库中添加唯一索引。 这是由于 uniq 验证在保存之前检查属性的值是唯一的,因此如果两个不同的数据库连接创建了两个具有相同值的记录,它不会引发错误。

【讨论】:

    猜你喜欢
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    相关资源
    最近更新 更多