ruby-on-rails – 仅在更改密码设置注册时需要密码

我有一个注册/编辑表单,通过我的应用程序中的Devise :: RegistrationsController呈现.它的工作方式现在,您必须在对表单进行任何更新时提供当前密码.他们希望它工作的方式是只在更新密码字段时才需要current_password …或者您必须重复“new_password”作为确认手段.我已经在Devise Wiki上做了一些阅读,主要是以下链接,他们似乎没有为此列出解决方案.如果有人对如何实现这一点有一些了解,我将不胜感激.

https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-password

https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-account-without-providing-a-password

解决方法

所以我一直在努力解决这个问题,我找到了解决方案.

在我的模型(user.rb)中,我添加了:validatable到以下代码片段:

devise :omniauthable,:database_authenticatable,:registerable,:recoverable,:rememberable,:validatable,:confirmable,:trackable,reset_password_keys:[:email,:company_id],request_keys: [:host,:params],omniauth_providers: [:auth0]

然后在我的注册控制器中,我添加了以下内容

def update_resource(resource,params)
  if !params[:password].blank?
    resource.password = params[:password]
    resource.password_confirmation = params[:password_confirmation]
  end

  resource.update_without_password(params)
end

最后在我的应用程序控制器中,我添加了:password_confirmation到以下代码段:

devise_parameter_sanitizer.permit(:account_update) do |u|
  u.permit(:first_name,:last_name,:email,:password,:password_confirmation,:phone_number,:receive_emails,location_attributes: [:id,:street,:city,:state,:zip,:country])
end

使用这种组合,一旦表单被提交,它将落入我已覆盖的update_resource块中.它将检查以确保resource.password和password_confirmation是相同的.最重要的是,current_password不在等式中,您不必每次都输入密码来保存更改.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...