2
1

More than 5 years have passed since last update.

Railsのdeviseでログインしている時に新規登録画面、ログイン画面へ行こうとしたらルートへ飛ばす

Posted at

やりたいこと

Railsのdeviseを使い、
「ログインしている状態」の時は
新規登録orログイン画面へ飛べないようにする。

動き

ログインしている時に
新規登録orログイン画面へ飛ぼうとしたら
ルートへ飛ばす。

実装方法

ルートを確認すると以下のようになっている。
新規登録 > sign_up > devise/registrasions#new
ログイン > sign_in > devise/sessions#new

image.png

上記2つのアクション時に
サインインしていたらルートへリダイレクトするように設定する。

コード

新規登録

app/controllers/users/registrations_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController
  # before_action :configure_sign_up_params, only: [:create]
  # before_action :configure_account_update_params, only: [:update]

  # GET /resource/sign_up
  # newの部分のコメントアウトを外し、redirect_toを追加
  def new
    redirect_to :root if user_signed_in?
    super
  end

  # POST /resource
〜〜〜〜〜
省略
〜〜〜〜〜

end

ログイン

app/controllers/users/sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
  # before_action :configure_sign_in_params, only: [:create]

  # GET /resource/sign_in
  # newのコメントアウトを外してリダイレクト、ifを入れる
  def new
    redirect_to :root if user_signed_in?
    super
  end

  # POST /resource/sign_in
〜〜〜〜
省略
〜〜〜〜

end
2
1
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
2
1