RoR 设计:使用用户名或电子邮件登录 [英] RoR Devise: Sign in with username OR email

查看:26
本文介绍了RoR 设计:使用用户名或电子邮件登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让用户能够使用电子邮件地址或用户名登录的最佳方式是什么?我正在使用warden + devise进行身份验证.我认为这样做可能不会太难,但我想我需要一些关于将所有需要的东西放在哪里的建议.也许设计已经提供了这个功能?就像在 config/initializers/devise.rb 中你会写:

What's the best way to enable users to log in with their email address OR their username? I am using warden + devise for authentication. I think it probably won't be too hard to do it but i guess i need some advice here on where to put all the stuff that is needed. Perhaps devise already provides this feature? Like in the config/initializers/devise.rb you would write:

config.authentication_keys = [ :email, :username ]

同时要求用户名和电子邮件才能登录.但我真的希望用户名和电子邮件只有一个字段,并且只需要其中之一.我将使用一些 ASCII 艺术将其形象化,它在视图中应该看起来像这样:

To require both username AND email for signing in. But i really want to have only one field for both username and email and require only one of them. I'll just visualize that with some ASCII art, it should look something like this in the view:

Username or Email:
[____________________]

Password:
[____________________]

[Sign In]

推荐答案

我已经找到了解决问题的方法.我对它不太满意(我宁愿有一种方法在初始化程序中指定它),但它现在有效.在用户模型中,我添加了以下方法:

I have found a solution for the problem. I'm not quite satisfied with it (I'd rather have a way to specify this in the initializer), but it works for now. In the user model I added the following method:

def self.find_for_database_authentication(conditions={})
  find_by(username: conditions[:email]) || find_by(email: conditions[:email])
end

正如@sguha 和@Chetan 指出的那样,官方设计 wiki 上提供了另一个很棒的资源.

As @sguha and @Chetan have pointed out, another great resource is available on the official devise wiki.

这篇关于RoR 设计:使用用户名或电子邮件登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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