确保您已经添加了用户名字段并将用户名添加到 attr_accessible。在用户中创建登录虚拟属性
1) 添加登录作为 attr_accessor
# Virtual attribute for authenticating by either username or email
# This is in addition to a real persisted field like 'username'
attr_accessor :login
2) 添加登录到 attr_accessible
attr_accessible :login
告诉设计在 authentication_keys 中使用 :login
修改 config/initializers/devise.rb 以具有:
config.authentication_keys = [ :login ]
在 Users 中覆盖 Devise 的 find_for_database_authentication 方法
# Overrides the devise method find_for_authentication
# Allow users to Sign In using their username or email address
def self.find_for_authentication(conditions)
login = conditions.delete(:login)
where(conditions).where(["username = :value OR email = :value", { :value => login }]).first
end
更新您的视图确保您的项目中有设计视图,以便您可以自定义它们
remove <%= f.label :email %>
remove <%= f.email_field :email %>
add <%= f.label :login %>
add <%= f.text_field :login %>