10
16

More than 5 years have passed since last update.

Rails: deviseでユーザ編集画面のパスワード入力を任意にする

Posted at
  • 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というメソッドもあるが、これは現在のパスワードを必須とするものなので、上記のように自前で実装する外ない様子。

deviseで現在のパスワード無しでuserを更新する - komagataのブログ

10
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
16