LoginSignup
50
47

More than 5 years have passed since last update.

devise ログイン後のリダイレクトについて(GET編)

Posted at

Rails の Devise でログイン後はログインする直前のページにリダイレクトさせます。

Deviseのデフォルト動き

before_action :authenticate_user!を通して、ログイン画面に遷移する場合、ログイン後、ログイン直前の画面に戻します。

下記のようなredirect_toを利用して、ログイン画面に遷移する場合、ログイン後、元の画面に戻らなくて、root_pathに遷移します。

unless user_signed_in?
   redirect_to  new_user_session_path

対策

ログイン直前のリクエストをセッションに保存しておいて、
ログイン成功後のafter_sign_in_path_forメソッドをオーバーライドして、戻る先をセッションから取得して設定します。
注意:ログイン関連のリクエストをセッションに入れないこと。

ログイン直前のリクエストをセッションに保存

applictaion_controller.rb
class ApplicationController < ActionController::Base
  after_action  :store_location
  def store_location
    if (request.fullpath != "/users/sign_in" &&
        request.fullpath != "/users/sign_up" &&
        request.fullpath !~ Regexp.new("\\A/users/password.*\\z") &&
        !request.xhr?) # don't store ajax calls
      session[:previous_url] = request.fullpath 
    end
end

deviseのリダイレクをカスタマイズ

devise標準のafter_sign_in_path_forをオーバーライドして、ログイン後のリダイレクト先はカスタマイズします。
SessionsControllerをカスタマイズしなければ、applictaion_controller.rbに追加します。
SessionsControllerをカスタマイズすれば、カスタマイズしたコントローラ中に追加します。

class UsersSessionsController < Devise::SessionsController
  ・・・
  def after_sign_in_path_for(resource)
    if (session[:previous_url] == root_path)
      super
    else
      session[:previous_url] || root_path
    end
  end
end

参照
https://github.com/plataformatec/devise/wiki/How-To:-Redirect-back-to-current-page-after-sign-in,-sign-out,-sign-up,-update
http://easyramble.com/friendly-forwarding-redirect-on-devise.html

50
47
1

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
50
47