0
1

More than 3 years have passed since last update.

[memo]ログインしているかどうかの判定

Posted at

user_signed_in?メソッド

ログインしているかどうかの判定を行うdeviseのメソッド

例:viewでログインしているときとそうでないときで表示を分ける場合に使う

app/views/layouts/application.html.erb
<% if user_signed_in? %>
 <div class="user_nav grid-6">
  <%= link_to "ログアウト", destroy_user_session_path, method: :delete %>
  <%= link_to "投稿する", new_tweet_path, class: "post" %>
 </div>
<% else %>
 <div class="grid-6">
  <%= link_to "ログイン", new_user_session_path, class: "post" %>
  <%= link_to "新規登録", new_user_registration_path, class: "post" %>
 </div>
<% end %>

redirect_toメソッド+unlessの条件分岐+exceptオプション

例:未ログイン状態のユーザーを転送させる場合に使用

controllerに記述
class TweetsController < ApplicationController
  before_action :move_to_index, except: [:index, :show] #index,showアクションを除く

  def index
    @tweets = Tweet.all
  end

  def new
    @tweet = Tweet.new
  end

〜〜省略〜〜

  def show
  end

  private

〜〜省略〜〜

  def move_to_index
    unless user_signed_in? #userがサインインしてない場合
      redirect_to action: :index
    end
  end
end

unless 条件式
  # 条件式がfalseのときに実行する処理
end 
0
1
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
1