2017-04-04 102 views
3

我有一個註冊/編輯表單,該表單通過我的應用程序中的Devise::RegistrationsController呈現。它的工作方式現在您必須提供您當前的密碼時,對窗體進行任何更新。我希望它能夠工作的方式是,只有當您更新password字段時才需要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

回答

1

所以我一直在試圖解決這個問題,我已經找到了解決方案。

以我模型(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.passwordpassword_confirmation是相同的。最重要的是,現在current_password不在等式中,您不必每次都輸入密碼來保存更改。

1

你可以做的是在用戶做更新其賬戶,通過PARAMS params[:user][:password]params[:user][:password_confirmation]時間來驗證:

這樣,如果有否passwordpassword_confirmation然後使用update_without_password方法通過user_params,另一種方法是否只使用update_attributes方法

def update 
    ... 
    if params[:user][:password].blank? && params[:user][:password_confirmation].blank? 
     if @user.update_without_password(user_params) 
     flash[:notice] = 'User updated successfully' 
     redirect_to some_path 
     else 
     render :edit 
     end 
    else 
     if @user.update_attributes(user_params) 
     # login before update passing the current user 
     sign_in(User.find(current_user.id), :bypass => true) 
     flash[:notice] = 'User updated successfully' 
     redirect_to some_path 
     else 
     render :edit 
     end 
    end 
    ... 
    end 
+0

我感謝你的幫助,這最終不適合我。我最終發佈了我找到的解決方案 –