简体   繁体   English

如何在 id 以外的 Rails 活动记录中创建唯一列

[英]how to make a unique column in rails active records other than id

class CreateUsers < ActiveRecord::Migration
   def up
     create_table :users do |t|
        t.string "email", :unique=>true

I was trying to add this unique option for making this email id unique in rails model but its not working so how can i make this email id unique ?我试图添加这个独特的选项,使这个电子邮件 ID 在 Rails 模型中唯一,但它不起作用,所以我怎样才能使这个电子邮件 ID 唯一?

The unique option should be passed to an add_index call, not where you define your column. unique选项应该传递给add_index调用,而不是您定义列的位置。

Update your migration definition as follows:更新您的迁移定义,如下所示:

class CreateUsers < ActiveRecord::Migration
   def up
     create_table :users do |t|
        t.string "email"
     end
     add_index :users, :email, unique: true
   end
   ...
end

And if you don't want to allow null then use t.string :email, null: false .如果您不想允许 null 则使用t.string :email, null: false

Update:更新:
Right now I would advise against ignoring the index on the database level, you could check the answer below to find out how to add a database unique index.现在我建议不要忽略数据库级别的索引,您可以查看下面答案以了解如何添加数据库唯一索引。

The reason this is not a good idea is because of the possibility of a race condition, when more than one thread/process of the application would get a request to insert the same data in almost the same time, both threads would check if the email already exists in the database or not, and both would find out that the email does not exist at that moment, so both will pass the #validate check, then both would proceed to insert.这不是一个好主意的原因是因为存在竞争条件的可能性,当应用程序的多个线程/进程几乎同时收到插入相同数据的请求时,两个线程都会检查电子邮件数据库中是否已经存在,并且两者都会发现当时电子邮件不存在,因此两者都将通过#validate检查,然后两者都将继续插入。
Then you would end up with having the same email in the database with no idea how that happened.然后你最终会在数据库中拥有相同的电子邮件,但不知道这是怎么发生的。

Having the validation is useful because you can react to the invalid record error in your controller.进行验证很有用,因为您可以对控制器中的无效记录错误做出反应。

Original Answer:原答案:
Why put restrictions on db level, I think putting a validation in the model level is more than enough, and at least whenever you need to change or remove restrictions you don't find your self needing to add a new migration为什么要在 db 级别设置限制,我认为在模型级别进行验证已经绰绰有余了,至少每当您需要更改或删除限制时,您都不会发现自己需要添加新的迁移

class User < ActiveRecord::Base
  validates :email, uniqueness: true
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM