未ログイン時にアクセスできないページの設定(before_action, skip_before_action)
前提
今回はgem 'sorcery'を使っている場合を想定
流れ
controllerごとに記載するのではなく、継承元の親クラス(application_controller)に記載することで処理を共通化できる。また他のコントローラーを実装する際には処理を忘れずに適用(何も記入しなければbefore_action適用、skip_before_actionを記入すればそちらの処理が適用される)させることができる。
コード記載
継承元の親クラスにbefore_actionを記載する
#application_controller class ApplicationController < ActionController::Base before_action :require_login private def not_authenticated redirect_to login_path, warning: t('defaults.message.not_authenticated') end end
個別コントローラーにはbefore_actionを適用させたくない場合のみ、skip_before_actionを記入
#app/controllers/user_sessions_controller.rb class UserSessionsController < ApplicationController skip_before_action :require_login, only: %i[new create] end