Ruby on Rails ActiveRecord 唯一性验证 [英] Ruby on Rails ActiveRecord uniqueness validation

查看:44
本文介绍了Ruby on Rails ActiveRecord 唯一性验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Rails 很陌生,正在阅读有关该主题的一些资源.我对此有一些疑问.好的,假设我们确实有一个模型,可以验证某些属性的唯一性:

I'm pretty new to Rails and was reading some resources on the subject. And I got some questions on it. Ok, let's say we do have a model, that validates some attribute uniqueness:

class User < ActiveRecord::Base
  attr_accesible :name
  validates :name, uniqueness: true
end

所以,我现在合理地期望,我将无法创建(或更准确地说——保存)两个具有相同名称的 User 实例到数据库中.但是,该资源确实坚持认为它仍然是可能的!

So, I reasonably expect now, that I will not be able to create (or to be more precise -- save) two User instances with the same name into the database. However, this resource does insist, that it is still possible!

  • 一些用户登录.
  • 多次点击登录"按钮
  • 请求 1 在内存中创建用户(有效)
  • 请求 2 在内存中创建用户(有效)
  • 请求 1 已成功保存
  • 请求 2 保存成功

后来此来源建议将数据库中的索引添加到名称"列并使其唯一.

And later on this source advises to add index in database to the 'name' column and make it unique.

但是,如果正如我之前所说的——验证发生在保存过程中,那么如何保存第二个请求?还是我丢了什么东西?

But, if as I said it before -- validation takes place upon save procedure, then how is it possible for the 2nd request to be saved? Or I've lost something?

(我提到的资源是 Rails 教程

推荐答案

在第一条记录保存到 DB 之前触发第二个请求,因此 rails 验证没有指定名称的记录并允许它保存.这就是为什么建议为数据库字段添加一个唯一字段,以避免这些边缘情况.

The second request is fired before the first record is saved in DB, so rails verifies that there isn't a record with the name specified an allows it to save. That's why it is recommended to add an unique to the database field, to avoid these edge cases.

或者换句话说,记录通过了内存中的验证.

Or in other words, the records passes the validations in memory.

这篇关于Ruby on Rails ActiveRecord 唯一性验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆