Rails 3. 验证电子邮件唯一性和区分大小写失败 [英] Rails 3. Validating email uniqueness and case sensitive fails

查看:23
本文介绍了Rails 3. 验证电子邮件唯一性和区分大小写失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Rails 3 中开发一个应用程序,在注册时我需要用户输入他们的电子邮件地址,我需要它是唯一的并且区分大小写.IE.当数据库中已经存在 MyEmail@yahoo.com 时,没有人应该能够注册 myEmail@yahoo.com.

I am developing an app in Rails 3 and upon signup I need the user to enter their email address and I need it to be unique and case sensitive. I.e. no one should be able to sign up with myEmail@yahoo.com when MyEmail@yahoo.com already exists in the database.

这是我的代码,它使应用程序崩溃:

This is my code and it crashes the app:

validates :email, :presence => true, :uniqueness => true, :case_sensitive => true,
                      :format => {:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i}

有什么问题吗?

推荐答案

请不要在此处使用区分大小写!!!.它将获取所有用户!因此,如果您有 100.000 个用户.首先它会用 LOWER(email) 获取它们.这可能非常慢,而且不会在电子邮件中使用您的索引.

Please dont use case sensitive there!!!. It will fetch all the users! So if you have 100.000 users. first it will fetch them all with LOWER(email). This can be VERY slow and it wont use your index on email.

这是我刚刚找到的一篇关于这个主题的文章:http:///techblog.floorplanner.com/post/20528527222/case-insensitive-validates-uniqueness-of-slowness

Here an article that i found just now about this topic: http://techblog.floorplanner.com/post/20528527222/case-insensitive-validates-uniqueness-of-slowness

我的建议是:运行查询使所有电子邮件都小写,并在验证前过滤器以小写电子邮件属性,这样您在该列中就没有任何大写字符.

My suggesting is: Run a query to make all the emails downcased and make a before validation filter to downcase the email attribute so you dont have any uppercased characters in that column.

User.update_all('email = LOWER(email)')

过滤前:

before_validation :downcase_email

private

def downcase_email
  self.email = email.downcase if email.present?
end

这篇关于Rails 3. 验证电子邮件唯一性和区分大小写失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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