LoginSignup
0
0

More than 3 years have passed since last update.

ログインしていない時は遷移先のアクションを制約する方法

Last updated at Posted at 2020-05-17

背景

今回は、ログインしていないユーザーが指定したページ以外遷移できないように制約をかける方法を紹介していきます。

やりたいこと

ログインしていないユーザーは、index,showページのみ遷移できて、newページやeditページに遷移しようとすると強制的にindexページに遷移されるように処理します。

使い方

コントローラー内で繰り返し使用されるコードは、private以下でメソッド化します。
以下の処理を行うことで、ユーザーがログインしていない状態でindex,showページ以外に遷移しようとすると、強制的にindexページに遷移されるようになります。

controller.rb
class PracticeController < ApplicationController
  before_action :move_to_index, except: [:index, :show]

  ~省略~

  private

  def  move_to_index
    redirect_to action: :index unless user_signed_in?
  end


以上

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