LoginSignup
11
11

More than 1 year has passed since last update.

Devise でフレンドリーフォワーディング

Last updated at Posted at 2017-12-21

Devise を使用するとログインした時にログイン前に開いていたページに戻る、いわゆるフレンドリーフォワーディングと呼ばれる機能が最初からある程度有効になっているようだが、 Ajax -> JS のコンボでログインページにリダイレクトしたりすると効かなくなることがある。
解決法は公式 wiki に書かれてる。

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :store_user_location!, if: :storable_location?
  # store_user_location!はauthenticate_user!より前に呼び出されている必要がある。
  before_action :authenticate_user!

  private

  def storable_location?
    # Turbo Framesを使う時はコメントを反転させる。
    request.get? && is_navigational_format? && !devise_controller? && !request.xhr?
    # request.get? && !turbo_frame_request? && is_navigational_format? && !devise_controller? && !request.xhr?
  end

  def store_user_location!
    store_location_for(:user, request.fullpath)
  end

  def after_sign_in_path_for(resource_or_scope)
    stored_location_for(resource_or_scope)
  end

  # ログアウトした時もフレンドリーフォワーディング
  def after_sign_out_path_for(resource_or_scope)
    stored_location_for(resource_or_scope)
  end
end
11
11
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
11
11