我使用Rails 4和Devise 3.2.4进行身份验证。
我试图允许用户在不提供密码的情况下更新其帐户(例如:姓名,电子邮件等)。
我已按照本教程 - > https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-account-without-providing-a-password
在完成教程所说的内容之后,我可以在不提供密码的情况下更新用户,但是当我想更改"密码时#34;本身,我不需要提供密码确认和当前密码。
如何允许用户更改名字,姓氏而不提供密码,更改密码时,用户需要输入密码,密码确认和当前密码。
请参阅下面的代码。
感谢。
如果:validatable
User Model
,我的代码似乎无法运作
class RegistrationsController < Devise::RegistrationsController
def update
account_update_params = devise_parameter_sanitizer.sanitize(:account_update)
if account_update_params[:password].blank?
account_update_params.delete("password")
account_update_params.delete("password_confirmation")
end
@user = User.find(current_user.id)
if @user.update_attributes(devise_parameter_sanitizer.sanitize(:account_update))
set_flash_message :notice, :updated
sign_in @user, :bypass => true
redirect_to @user
else
render "edit"
end
end
protected
end
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:account_update) { |u|
u.permit(:firstname, :lastname, :password, :password_confirmation )}
end
end
答案 0 :(得分:0)
用此代码替换您的注册控制器
class RegistrationsController < Devise::RegistrationsController
def update
@user = User.find(current_user.id)
successfully_updated = if needs_password?(@user, params)
@user.update_with_password(devise_parameter_sanitizer.sanitize(:account_update))
else
# remove the virtual current_password attribute
# update_without_password doesn't know how to ignore it
params[:user].delete(:current_password)
@user.update_without_password(devise_parameter_sanitizer.sanitize(:account_update))
end
if successfully_updated
set_flash_message :notice, :updated
# Sign in the user bypassing validation in case his password changed
sign_in @user, :bypass => true
redirect_to after_update_path_for(@user)
else
render "edit"
end
end
private
# check if we need password to update user data
# ie if password or email was changed
# extend this as needed
def needs_password?(user, params)
user.email != params[:user][:email] ||
params[:user][:password].present?
end
end
使用此代码,您需要在更改密码和电子邮件时输入密码,并且在更改任何其他信息时不需要密码