パスワード変更機能を、Devise が提供するコントローラーを使わずに、自前で実装したいときのためのメモ。
現在のパスワード・新しいパスワード・新しいパスワード(確認用) を入力して変更する場合、
update_with_password を使う。
current_user.update_with_password(
password: "new_password",
password_confirmation: "new_password",
current_password: "old_password"
)
新しいパスワードで強制的に変更する場合、update を使う。
管理者がユーザーのパスワードを再発行するときなんかに使ったりする。
current_user.update(
password: "new_password",
password_confirmation: "new_password"
)
注意点としては、現在ログインしているユーザーのパスワードを変更すると、
直後ログアウトした状態になってしまうので、
再ログインする処理が必要。
class SettingsController < ApplicationController
def update
respond_to do |format|
if current_user.update_with_password(user_params)
sign_in(current_user, bypass: true)
format.html { redirect_to edit_setting_path }
else
format.html { render :edit }
end
end
end
end