貼code

2017年2月6日 星期一

rails devise 使用者編輯資料時免當前密碼

    在開發rails 網站時,常常會用到devise這個gem來負責處理使用者的部分。
而devise預設的edit功能是需要輸入當前密碼的。有些情況下不希望如此,就可以利用以下方法(客製化devise 的controller)

首先 在 config/routes.rb 裡,加入
devise_for :users, controllers: { registrations: 'users/registrations' }
(如果devise:controller 的scope 是 users的話,即rails g devise:controllers users )

再來在users/registrations_controller.rb裡,加上
protected
def update_resource(resource, params)
    params.delete :current_password
    resource.update_without_password(params)
end

最後把edit.html.erb頁面裡的current password欄位拿掉就可以摟!!

===2017.2.12更新
後來發現這樣做的話,密碼就不能改了OAO
所以把registration_controller裡改一下
變成current_password的欄位還是show出來
然後判斷,如果current欄位跟new_password都是空的
那就不用current_password 就可以改其他資料
protected
  
def update_resource(resource, params)
  if params[:current_password].blank? && params[:password].blank?
    resource.update_without_password(params.except(:current_password))
  else
    super
  end
end


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

沒有留言:

張貼留言