LoginSignup
53
70

More than 5 years have passed since last update.

Deviseでサインイン/サインアウト後のリダイレクト先を変更する

Posted at

Deviseで複数のログイン機能を実装している際、サインインやサインアウト後のリダイレクト先が正しく遷移しません。
(例えば一般ユーザーのルートをroot_path、管理者ユーザーのルートをadmin_root_path などと設定している場合、管理者のサインアウト後も root_pathにリダイレクトされてしまいます)

DeviseのWikiを調べてみたところ対処法が載っていました。
Devise::Controllers::Helpersの after_sign_in_path_forafter_sign_out_path_for をそれぞれオーバーライドしてリダイレクトURLを返すようにすれば良いそうです。

config/application.rb

class ApplicationController < ActionController::Base

 ~(省略)~

  private

  # ログイン後のリダイレクト先
  def after_sign_in_path_for(resource_or_scope)
    if resource_or_scope.is_a?(AdminUser)
      admin_root_path
    else
      root_path
    end
  end

  # ログアウト後のリダイレクト先
  def after_sign_out_path_for(resource_or_scope)
    if resource_or_scope == :admin_admin_user
      new_admin_admin_user_session_path
    else
      new_user_session_path
    end
  end
end

参考

How To: Change the redirect path after destroying a session i.e. signing out

53
70
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
53
70