- deviseを使っている
- adminユーザに全ユーザのアカウント管理画面を作っている
- adminはユーザのパスワードを知らないので、現在のパスワードの入力なしにユーザのパスワードを変更できるようにしたい
controllers/users_controller.rb
def update
p user_params
respond_to do |format|
if @user.update_without_current_password(user_params)
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
Userモデルに下記メソッドを追加:
models/user.rb
def update_without_current_password(params, *options)
params.delete(:current_password)
if params[:password].blank?
params.delete(:password)
params.delete(:password_confirmation) if params[:password_confirmation].blank?
end
clean_up_passwords
update_attributes(params, *options)
end
deviseのデフォルトでupdate_with_password
というメソッドもあるが、これは現在のパスワードを必須とするものなので、上記のように自前で実装する外ない様子。