且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

RoR的设计:登录使用用户名或电子邮件

更新时间:2022-10-26 07:44:07

我已经找到了解决问题的办法。我不是很满意呢(我宁愿有一个方法来指定这个在初始化),但它的作品现在。在用户模型中添加以下方法:

 高清self.find_for_database_authentication(条件= {})
  find_by(用户名:条件[:邮箱])|| find_by(电子邮件:条件[:邮箱])
结束

由于@sguha和@Chetan指出,another巨大的资源可在官方色器件维基。

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 ]

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 and @Chetan have pointed out, another great resource is available on the official devise wiki.