以大多数网站工作的方式,我在数据库中存储“UsErNaMe”,但让用户使用“用户名”登录.
这是一个相当明显和必要的功能,很多人似乎已经问过,但是我仍然绊倒的解决方案似乎与Devise自己的文档无关.
例如,考虑这个博文:http://anti-pattern.com/2011/5/16/case-insensitive-keys-with-devise
[…]you’ve probably run into the problem that some users like to type
certain letters in their logins (email and/or username) in uppercase,
but expect it to be case-insensitive when they try to sign in. A not
unreasonable request[…]
凉!这就是我想要的.
他的解决方案
# config/initializers/devise.rb Devise.setup do |config| config.case_insensitive_keys = [:email,:username] end
这是我一直在找的解决方案.但这里是该配置选项的文档:
# Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [ :username,:email ]
特别是:“这些键将在创建/修改用户时被降级”.换句话说,数据库中的用户名正在缩减.
核实:
User.create username: "UsErNaMe",password: "secret",email: "email@com.com" #=> <User username="username"...>
我错过了一些很明显的东西吗?
解决方法
从
devise wiki:您需要在模型中覆盖devise的find_first_by_auth_conditions方法.
ActiveRecord示例:
def self.find_first_by_auth_conditions(warden_conditions) conditions = warden_conditions.dup if login = conditions.delete(:login) where(conditions).where(["lower(username) = :value OR lower(email) = :value",{ :value => login.downcase }]).first else where(conditions).first end end