使用user_name登录设计

时间:2011-03-17 17:51:29

标签: ruby-on-rails-3 authentication devise

我想使用设计进行身份验证,而不是将电子邮件作为登录信息,我希望用户使用其用户名

表示

我已将user_name添加到users表中 添加到用户模型attr_accessible:email,:password,:password_confirmation,:remember_me,:user_name

以及'/intilizers/devise.rb'中的config.authentication_keys = [:user_name]

但我的问题是如何跳过电子邮件验证并改为使用user_name

我正在使用rails3和设备1.1.8

提前致谢

欢呼声

sameera

3 个答案:

答案 0 :(得分:17)

在最近的Devise版本中,你可以添加email_required吗?您的用户模型的方法。 它关闭了可验证模块中的电子邮件验证。

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  def email_required?
    false
  end
end

答案 1 :(得分:3)

Devise没有预见到根本没有电子邮件字段的选项,因此必须在Rails级别上完成。

不幸的是,Rails没有提供如何删除验证的方法,但是可以扩展rails并且这已经在this plugin中完成了,只需看一下active_record extension,这是非常简单的

基本上,您将验证删除功能添加到active_record

module ActiveRecord
  class Base
    def self.clear_validations
      @validate_callbacks = []
    end  
    def self.remove_validation(sym)
     @validate_callbacks.reject! {|validation| validation.options[:name] == sym}
    end
    def self.remove_validation_group(sym)
     @validate_callbacks.reject! {|validation| validation.options[:group] == sym}
    end
  end
end 

并扩展设计的用户模型以删除电子邮件验证

require 'active_record_validation_extender'

module UserValidationExtender
  def self.included(base)
    base.class_eval do
      base.remove_validation(:email)
    end    
  end
end

答案 2 :(得分:0)

Devise提供了有关如何进行设置的说明。

如果您想使用用户名(或其他)而不是电子邮件,请查看此内容。 (请记住,您仍然需要在注册页面上要求发送电子邮件) https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-with-something-other-than-their-email-address

如果您想使用电子邮件或用户名,请查看此内容。

https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address