我目前有一个具有额外属性的用户,我希望他们能够在不输入当前密码的情况下进行更新。
所以我必须创建自己的RegistrationsController并覆盖更新方法。 (摘自Devise github页面)。
def update
account_update_params = devise_parameter_sanitizer.sanitize(:account_update)
# required for settings form to submit when password is left blank
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(account_update_params)
set_flash_message :notice, :updated
# Sign in the user bypassing validation in case their password changed
sign_in @user, :bypass => true
redirect_to edit_user_registration_path
else
render 'edit'
end
end
但是现在,如果他们想要更改密码,我想要求他们输入正确的当前密码。这似乎是一个问题,因为如果他们确实输入了他们当前的密码,我必须将其添加到允许的参数。但后来它告诉我current_password不是用户的有效属性。
def configure_permitted_parameters
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:name, :email, :attr1, :attr2,
:password, :password_confirmation) }
end
答案 0 :(得分:0)
使用update_with_password
和update_without_password
mehotds
with_password = params[:current_password].present?
if @user.update_user(with_password)
set_flash_message :notice, :updated
# Sign in the user bypassing validation in case their password changed
sign_in @user, :bypass => true
redirect_to edit_user_registration_path
else
render 'edit'
end
private
def update_user(with_password)
if with_password
@user.update_with_passoword(account_update_params)
else
@user.update_passoword(account_update_params)
end
end