gpt4 book ai didi

ruby-on-rails - Rails "validates_uniqueness_of"区分大小写

转载 作者:行者123 更新时间:2023-12-03 05:01:09 25 4
gpt4 key购买 nike

这是模型(我使用的是 SQLLite3):

class School < ActiveRecord::Base

validates_uniqueness_of :name

end

例如,在添加“Yale”后,我无法添加“Yale”,但可以添加“yale”。如何使验证不区分大小写?

编辑:找到它 - Active Record Validations

最佳答案

validates_uniqueness_of :name, :case_sensitive => false 可以解决问题,但您应该记住 validates_uniqueness_of 并不能保证唯一性,如果您有多个服务器/服务器进程(例如运行 Phusion Passenger、多个 Mongrel 等)或多线程服务器。这是因为您可能会得到以下事件序列(顺序很重要):

  1. 进程 A 收到创建名为“foo”的新用户的请求
  2. 进程 B 执行相同的操作
  3. 进程 A 通过询问数据库该名称是否存在来验证“foo”的唯一性,而数据库表示该名称尚不存在。
  4. 进程 B 执行相同的操作并获得相同的响应
  5. 进程 A 提交新记录的 insert 语句并成功
  6. 如果数据库约束要求该字段具有唯一性,进程 B 将提交新记录的 insert 语句,然后失败,并返回一个丑陋的服务器异常来自 SQL 适配器。如果没有数据库约束,插入将会成功,并且现在有两行名称为“foo”。

另请参阅 validates_uniqueness_of 中的“并发性和完整性” Rails 文档。

来自Ruby on Rails 3rd Edition :

...despite its name, validates_uniqueness_of doesn’t really guarantee that column values will be unique. All it can do is verify that no column has the same value as that in the record being validated at the time the validation is performed. It’s possible for two records to be created at the same time, each with the same value for a column that should be unique, and for both records to pass validation. The most reliable way to enforce uniqueness is with a database-level constraint."

另请参阅this programmer's experiencevalidates_uniqueness_of

这种情况常见的一种情况是创建新帐户时意外地从网页重复提交。这是一个很难解决的问题,因为用户将得到第二个(丑陋的)错误,这会让他们认为他们的注册失败,而实际上它成功了。我发现防止这种情况的最好方法就是使用 javascript 来尝试防止重复提交。

关于ruby-on-rails - Rails "validates_uniqueness_of"区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/690664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com