4
4

More than 3 years have passed since last update.

ログイン後の遷移先を変更する方法

Last updated at Posted at 2021-08-30

内容

deviseを用いてログイン機能を実装し、特に何も設定していないと root_path で指定したページに遷移すると思います。
そこで、ログインやゲストログイン後の遷移先を自由に指定する方法を紹介します。

ログイン後の遷移先の指定

application_controller.rb
class ApplicationController < ActionController::Base
  before_action :authenticate_user!

  #以下のメソッドを記入
  def after_sign_in_path_for(resource)
    prefix_path #遷移させたいページのpathを記述
  end
end

/users/application.rb に after_sign_in_path_forメソッドを用いて、ログイン、サインイン後に遷移させたいページのprefix_pathを指定することで変更できます。

ゲストログイン後の遷移先の指定

sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
  def guest_sign_in
    # ゲストアカウントでログイン
    sign_in User.guest
    # 以下を変更
    redirect_to prefix_path #遷移させたいページのpathを記述
  end
end

ゲストログイン後の遷移先は、users/sessions_controller.rb のredirect_to でpathを指定することで変更できます。

4
4
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
4
4