我正在使用 Devise for Rails。在默认注册过程中,Devise 要求用户输入两次密码以进行验证和认证。我怎样才能禁用它?
9 回答
要禁用密码确认,您只需password_confirmation
从注册表单中删除该字段即可。这消除了完全确认密码的需要!
- 如果您还没有生成设计视图:
rails g devise:views
- 删除中的
password_confirmation
部分app\views\devise\registrations\new.html.erb
这个工作的原因在于lib/devise/models/validatable.rb
设计源:
module Devise
module Models
module Validatable
def self.included(base)
base.class_eval do
#....SNIP...
validates_confirmation_of :password, :if => :password_required?
end
end
#...SNIP...
def password_required?
!persisted? || !password.nil? || !password_confirmation.nil?
end
end
end
end
请注意,只有在password_required?
返回时才会触发验证true
,并且如果字段是password_required?
将返回。false
password_confirmation
nil
因为password_confirmation
表单中存在该字段的位置,它将始终包含在参数 hash 中,如果它留空,则作为空字符串,将触发验证。但是,如果您从表单中删除输入,password_confirmation
则参数中的 将为nil
,因此不会触发验证。
看来,如果您只是从模型中删除 attr_accessible 要求,没有它就可以正常工作。
顺便说一句,我同意这种做法,在极少数情况下出现拼写错误,用户可以简单地使用密码恢复来恢复他们的密码。
我不熟悉设计,但如果您可以在保存/验证之前访问控制器中的模型,您可以执行以下操作
model.password_confirmation = model.password
model.save
为了找到这个问题的 Rails 4 用户,只需:password_confirmation
从允许的参数中删除,您在ApplicationController.rb
.
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:username, :email, :password)
end
devise_parameter_sanitizer.for(:account_update) do |u|
u.permit(:username, :email, :password)
end
end
最简单的解决方案:
删除:validable from
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable,
:confirmable, :timeoutable, :validatable
;)
您只需从表单中删除 password_confirmation 字段。
见维基
def update_with_password(params={})
params.delete(:current_password)
self.update_without_password(params)
end
设计的默认验证(lib/devise/models/validatable.rb):
validates_confirmation_of :password, :if => :password_required?
和方法:
def password_required?
!persisted? || !password.nil? || !password_confirmation.nil?
end
我们需要覆盖设计默认密码验证。将以下代码放在最后,以免它被任何 Devise 自己的设置覆盖。
validates_confirmation_of :password, if: :revalid
def revalid
false
end
你的模型看起来像这样:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable,
:confirmable, :timeoutable, :validatable
validates_confirmation_of :password, if: :revalid
def revalid
false
end
end
然后从注册表单中删除password_confirmation字段。
我认为这是禁用密码确认的简单方法: https ://github.com/plataformatec/devise/wiki/Disable-password-confirmation-during-registration
一些用户希望使注册过程更短、更容易。可以删除的字段之一是密码确认。
最简单的解决方案是:您可以简单地从位于 devise/registrations/new.html.erb 的注册表单中删除 password_confirmation 字段(如果您使用的是 HAML,则为 new.html.haml),这样就无需完全确认密码了!
原因在于设计源代码中的 lib/devise/models/validatable.rb :
请注意,只有在 password_required 时才会触发验证?返回 true,并且 password_required?如果 password_confirmation 字段为 nil,将返回 false。
因为表单中存在 password_confirmation 字段,所以它总是包含在参数 hash 中,如果它留空,则作为空字符串,触发验证。但是,如果您从表单中删除输入,则参数中的 password_confirmation 将为 nil,因此不会触发验证。