如何为Rails 3编写不区分大小写的find_by_email [英] how can I write a case-insensitive find_by_email for Rails 3
问题描述
我发现,如果用户在执行以下操作时注册了电子邮件并在其电子邮件中使用大写字母,那么我将无用。
I found that if a user registers with an email and use a capital letter in their email when I do the following I get nil.
示例:
username = Dillan@example.com
params[:user][:email] = dillan@example.com
user = User.find_by_email(params[:user][:email])
user.nil?
=>是
我如何搜索电子邮件时不存在区分大小写的问题,或者我如何写不区分大小写的find_by_email?
How can I search for an email without the problems of case sensitivity or how an I write a find_by_email that is case insensitive?
推荐答案
如果用户(例如X)有一封电子邮件 Dillan@example.com,然后
If a user(say X) has an email 'Dillan@example.com', then
User.find(:all, :conditions => ["lower(email) =?", "dillan@example.com"])
应该返回用户X。我没有复制这种情况,但是我想这实际上是您需要做的。
should return the user X. I didnt replicate the situation but that is what I guess you essentially need to do.
或者,更好的是,使用where代替找到的指针@MrTheWalrus
Or, more better, use where instead of find as pointed out by @MrTheWalrus
User.where('lower(email) = ?', "dillan@example.com").first
这篇关于如何为Rails 3编写不区分大小写的find_by_email的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!