LoginSignup
4
5

More than 3 years have passed since last update.

[rails devise]ログインしていないユーザーをログインページへ遷移する方法

Posted at

前提 今回はitemsコントローラーでの操作にする。

class ItemsController < ApplicationController
  before_action :move_to_signed_in, except: [:index]
  def index
    # トップページ生成
  end

private
  def move_to_signed_in
    unless user_signed_in?
      #サインインしていないユーザーはログインページが表示される
      redirect_to  '/users/sign_in'
    end
  end

before_actionの使い方

before_action :move_to_signed_in, except: [:index]

before_action→コントローラで定義されたアクションが実行される前に、指定した共通の処理を行うことができるメソッドのこと。
except: [:index]→indexアクションは除く
・indexアクションを除き他のアクションが実行された時move_to_signed_inの処理を行う。つまりトップページが表示されているときはmove_to_signed_inの処理は実行されない

move_to_signed_inの実行内容

def move_to_signed_in
    unless user_signed_in?
      #サインインしていないユーザーはログインページが表示される
      redirect_to  '/users/sign_in'
    end

user_signed_in?→ユーザーがログインしているかどうか判別する
unless→「もし~でないならば」
unless user_signed_in?→もしユーザーがログインしていないのなら
redirect_to '/users/sign_in'→ログインページに画面遷移する

まとめ

indexアクション以外のアクション(createなど)をユーザーが実行しようとしたら
ログインしているユーザーかどうか判別する。
ユーザーがログインしていなかったらログインページ(/users/sign_in)に画面遷移する
ログインできていたらユーザーが指定したアクションが実行できる

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