LoginSignup
1
0

More than 3 years have passed since last update.

ログイン状態かどうかの表示と設定の仕方

Last updated at Posted at 2020-03-06

ログイン状態かどうかの表示

【例】gem'devise'をbundleしたあと(モデルをPost、ビューはapplication.html.erbに記述するとします)

app/views/layouts/application.html.erb
<% if user_signed_in? %>
          <div class="XXXX">
            <%= link_to "ログアウト", destroy_user_session_path, method: :delete %>
            <%= link_to  "投稿する", "/posts/new", class: "YYYY" %>
          </div>
        <% else %>
          <div class="ZZZZ">
            <%= link_to "ログイン", new_user_session_path, class: 'YYYY' %>
            <%= link_to "新規登録", new_user_registration_path, class: 'YYYY' %>
          </div>
        <% end %>

if user_signed_in?はユーザーがログイン済かどうかを判定します。
ログイン済のときは"ログアウト""投稿する"を表示されます。
elseはそのほかという意味なので(今回はログインしていないとき)"ログイン""新規登録"が表示されます。

コントローラーにリダイレクトを設定

このままだと未ログインユーザーであっても直接/posts/newというパスにアクセスすることで投稿ができてしまいます。
そこで、未ログインユーザーが投稿画面など直接アクセスしてきた際にはルートパスに遷移するように設定を行います。
posts_controller.rbの全てのアクションに対して、もし、ユーザーがログインしていなかったらindexアクションにリダイレクトするように実装します。

app/controllers/posts_controller.rb
class TweetsController < ApplicationController
  before_action :move_to_index, except: [:index, :show]
〜略〜
 def move_to_index
    redirect_to action: :index unless user_signed_in?
  end
end

before_actionにより先にmove_to_indexメソッドが動いてindexアクションのindex.html.erbのページにリダイレクトしてくれます。
indexアクションにアクセスした時、indexアクションへのリダイレクトを繰り返し無限ループが起こるので、except: :indexを付け加えます。今回はshowも詳細ページへはログインする必要はないものとします。
unless文で先にuser_signed_in?を判定をします。
つまり、ユーザーがログインしていない時にはindexアクションを実行する。ということになります。

unless文

unless文は条件式が偽の場合の処理を記述するのに使われます。

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