【Rails】devise - アカウント作成・更新後のリダイレクト遷移先をカスタマイズする

内容

Ruby on Railsgem 'devise'
アカウント作成・更新した後のリダイレクト遷移先のパスの変更の方法

前提

① deviseの登録・認証を使用するモデル設定

$ rails g devise User

② deviseのコントローラのルーティング

Rails.application.routes.draw do
  devise_for :users,
    controllers: { 
      registrations: 'registrations',
    }

デフォルト設定

devise本家では
アカウント作成した後のデフォルトのリダイレクト遷移先は
次のように定義されています

いつ デフォルトの遷移先パス 遷移先パスを定義しているメソッド
アカウント作成後
(Devise::RegistrationsController#create)
after_sign_in_path_for(resource)と同じパス after_sign_up_path_for(resource)
アカウント更新後
(Devise::RegistrationsController#update)
signed_in_root_path(resource)
new_session_path(resource)
(条件分岐)
after_update_path_for(resource)

カスタマイズ

デフォルトの遷移先パスから変更したい場合は、
ソースコードで定義されている
after_sign_in_path_for メソッド
after_update_path_forメソッド
をオーバーライドします

カスタマイズの例
class RegistrationsController < Devise::RegistrationsController

  protected
  
  def after_update_path_for(resource)
    user_path(resource)
  end

  def after_sign_up_path_for(resource)
    users_path
  end

end