1
0

More than 1 year has passed since last update.

[Devise] 更新をpasswordなしで可能にする

Last updated at Posted at 2022-03-11

はじめに

認証機能で有名なRuby on Railsの gem Deviseを使ったので記事を残そうと思います。
update_without_passwordを使った方法はpasswordの更新ができなくなってしまうので、update_without_current_passwordというメソッドを自作して適応します。
これによりpassword自体の変更も可能にします。

環境

M1 Mac
VScode
ruby 3.1.0
rails 6.0.4.7
devise 4.8.1

routingを追加

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

registrations_controllerを追加

terminal
# vscodeを使っている場合は下記で作成+開く
$ code app/controllers/registrations_controller.rb

# unixコマンドを使う場合下記で作成したのち開いてください
$ touch app/controllers/registrations_controller.rb
app/controllers/registrations_controller.rb
# 下記の内容を追加
class RegistrationsController < Devise::RegistrationsController

  protected

  def update_resource(resource, params)
    resource.update_without_current_password(params)
  end
  
  # ユーザー詳細ページをリダイレクト先に設定
  def after_update_path_for(resource)
    user_path(resource)
  end
end

Userモデルにメソッドを追加

app/models/user.rb
def update_without_current_password(params, *options)

  if params[:password].blank? && params[:password_confirmation].blank?
    params.delete(:password)
    params.delete(:password_confirmation)
  end

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

終わりに

registrations_controllerを追加で個別にコントローラーを作成せずにrails g devise:controllers usersコマンドを利用する場合

routineは下記になります

routes.rb
devise_for :users, 
  controllers: { registrations: 'users/registrations' }
# usersが増えていますね。 
# touchコマンドで生成すればusersディレクトリが作成されないので階層を深くせずに済みます

参考

1
0
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
1
0