簡體   English   中英

更新設計帳號時當前密碼不能為空

[英]Current password can't be blank when updating devise account

我正在使用devise ,我想允許用戶更新他的帳戶(電子郵件和密碼)。 因此,當我單擊edit_user_registration_path ,我得到一個頁面,用戶可以在其中更改其電子郵件和密碼。 但是在提交此update表單時,我不斷收到以下消息:

1 error prohibited this user from being saved: ×
Current password can't be blank

在我的ApplicationController ,我有

def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:name, :surname, :email, :user_name, :terms_of_service, :password, :password_confirmation) }
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:email, :password, :password_confirmation) }
end

有人可以解釋嗎?

默認情況下,Devise在edit_user_registration上具有三個密碼字段:password,password_confirmation和current_password: default registrations / edit.html.erb

任何更改都必須使用current_password; 如果不希望更改密碼,則其他兩個可以保留為空白。

將此代碼放在您的用戶模型中:

def update_with_password(params, *options)
    current_password = params.delete(:current_password)

    if params[:password].blank?
      params.delete(:password)
      params.delete(:password_confirmation) if params[:password_confirmation].blank?
    end

    result = if params[:password].blank? || valid_password?(current_password)
      update_attributes(params, *options)
    else
      self.assign_attributes(params, *options)
      self.valid?
      self.errors.add(:current_password, current_password.blank? ? :blank : :invalid)
      false
    end

    clean_up_passwords
    result
end

默認情況下,devise需要密碼才能更新用戶。

這是帶有更改此行為的官方說明的頁面: https : //github.com/plataformatec/devise/wiki/How-To :-Allow-users-to-edit-their-account-without-providing-a-password

我不知道您是否有解決方案,但是您可以做一個簡單的事情:

創建一個user_controller,然后創建一個具有password和password_confirmation的user_params,以及另一個沒有密碼和password_confirmation的用戶名(我使用此名稱:user_params_without_password)。

並且在更新中,您將檢查是否存在密碼,是,將使用user_params,如果沒有,則使用user_params_without_password。

這是代碼:

def update

    if params[:user][:password].present?
      params = user_params
    else
      params = user_params_without_password
    end

def user_params
      params.require(:user).permit( params...

def user_params_without_password
  params.require(:user).permit( params without password

我希望這個提示可以對您有所幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM