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

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

问题描述

使用者可以使用他们的电子邮件地址或用户名登录什么?我正在使用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

As @sguha和@Chetan已经指出,另一个伟大的资源可在官方的设计维基上获得。

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

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

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