46
45

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsでログイン前にいたページを維持する

Posted at

ログイン時のページ遷移

見てた所に戻れないとイヤですよね。

store_location

ApplicationControllerbefore_filterとしてstore_locationと言う名前で、ユーザが居た場所を覚えておきます。

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_filter: store_location

  def store_location
    session[:return_to] = request.url
  end

end

redirect_back_or(default)

SessionsControllerSessionsHelperredirect_back_or(default)と言う名前で、ユーザが居た場所を覚えていればその場所に、無ければデフォルトに飛ばす、としておきます。

# app/controllers/sessions_controller.rb | app/helpers/sessions_helper.rb
  def redirect_back_or(default)
    redirect_to(session[:return_to] || default)
    session.delete(:return_to)
  end

skip_before_filter

後は保存されているlocationを呼び出したいcontrollerでredirect_back_orを利用すればOKです。
変な場所にredirectされる場合は、利用するcontroller部分でskip_before_filterを使い、store_locationを走らせないようにしておくと幸せになれるかも知れません。
仮にSessionsControllerとする場合は

# app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
  skip_before_filter :store_location

  def create
    # login user
    redirect_back_or root_url
  end
end

と言った感じですね。

46
45
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
46
45

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?