LoginSignup
8
8

More than 5 years have passed since last update.

routes.rbでログイン状態によってroutesを切り替える

Posted at

はじめに

ログイン状態によって飛ばしたいページが異なることは多々あると思います

  • ログインしているかどうかでrootを変えたい
  • ログインしてない場合にアクセスできるページとできないページがある

みたいな場合、Controllerでログイン状態をチェックした後適切なページにリダイレクトさせる、といった処理をさせることが多いと思うんですが、routeファイルでその辺りまでハンドリングできるとControllerがすっきりして良いなと思いました

環境は以下のとおりです
- Rails 4.2.5
- Warden 1.2.6

Custom Constraints を作る

Constraintsは独自で定義できるので、ログイン状態かどうかをチェックする制約を作成します
wordenを使っている場合、以下のようになります

class NotLoginConstraint
  def matches?(request)
    !request.env['warden'].authenticated?
  end
end

class LoginConstraint
  def matches?(request)
    request.env['warden'].authenticated?
  end
end

routesを定義する

あとは先程作った制約を使ってroutesを定義するだけです
各定義は例なので適当です

Rails.application.routes.dra do
  # ログインに関係なくアクセス可能なページの定義
  get 'hoge', to: 'hoge#index' 

  constraints NotLoginConstraint.new do
    # ログインしていない場合のrootの定義
    get '', to: 'welcome#index'

    # ログインしていない場合にアクセス可能なページの定義
    get 'login', to: 'session#new'
  end

  constraints LoginConstraint.new do
    # ログインしている場合のrootの定義
    get '', to: 'user#show'

    # ログインしている場合にアクセス可能なページの定義
    get 'logout', to: 'session#destroy'
  end

  # マッチしなかった場合のリダイレクト先の定義
  match '*unmatched_route', to: redirect('/'), via: :all
end

rootの定義は、rootメソッドを使うと上書きできないため、get ''として設定しています

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