LoginSignup
6
4

More than 3 years have passed since last update.

Rails Deviseでユーザー編集を現在のパスワードを入力しないで更新する

Posted at

個人の備忘録

#背景
railsでユーザー登録のためにdeviseを使った簡単なプリを作成中に編集画面で
現在のパスワードを入れないで更新できないかと考えたため。

環境

rails 5.2.3
ruby 2.6.3

まずdeviseを用いた際のルーティングを確認

config/routes.rb
devise_for :users, controllers: {
        registrations: 'users/registrations',
        sessions: 'users/sessions'
      }

特に問題なさそう

registrations_controller.rbに下記を記載

registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
  before_action :authenticate_user!

  protected

  *この部分を記載
  def update_resource(resource, params)
    resource.update_without_current_password(params)
  end

  (省略)

end

受けとったリソースを、update_without_current_passwordメソッド(Userモデルに後で実装します)で
パスワード抜きで更新できるようにし、引数にparamsを指定してリソースの中身を更新しています。

User モデルに update_without_current_password を実装

一個前でregistration_controllerに自力で定義したメソッドを使えるようにモデルに定義していく

models/user.rb
def update_without_current_password(params, *options)
    params.delete(:current_password)   *params.delete(:current_password) で current_password のパラメータを削除。

    if params[:password].blank? && params[:password_confirmation].blank?   *パスワード変更のためのパスワード入力フィールドとその確認フィールドの両者とも空の場合のみ、パスワードなしで更新できるようにするためです。

      params.delete(:password)
      params.delete(:password_confirmation)
    end

    result = update_attributes(params, *options)
    clean_up_passwords
    result
  end

あとはビューのフォームを消すだけ

パスワードのフォームを削除して終了

参考にしたサイト
Devise でユーザーがパスワードなしでアカウント情報を変更するのを許可
Deviseでパスワードの入力無しでユーザー情報の更新をする方法

6
4
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
6
4