8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

deviseのヘルパーメソッドについて

Last updated at Posted at 2019-09-09

はじめに

deviseを導入した際に使えるようになる、便利なヘルパーメソッドについて、備忘録として投稿します。

deviseとは

ユーザーの新規登録、ログイン、ログアウトなど、認証に必要な機能を追加することができるgemです。

deviseの導入方法について

【参照】
https://qiita.com/cocoa-engineer/items/625da569fcac1ad2db1f

deviseのヘルパーメソッド

deviseを導入すると、以下の機能が使えるようになります。

メソッド 機能
before_action :authenticate_user! ログイン済ユーザーのみにアクセスを許可する
current_user 現在ログインしているユーザーを取得する
user_signed_in? ユーザーがサインインしているかどうかを判定する
user_session ユーザーのセッション情報にアクセスする

※「user」の部分はモデル名になるので、モデル名に応じて「user」部分を書き換えてください。

各ヘルパーメソッドの使い方については、以下のとおりです。

before_action :authenticate_user!

特定のアクションを、ログイン済みユーザーでないとアクセスできないようにするため、以下のようにコントローラ内に設定します。
※ログインしていない場合は、ログインページにリダイレクトされます。

class SampleController < ApplicationController
  before_action :authenticate_user!, only: [:show]

  def index
  end

  def show
  end
end

このようにonlyを使うと、showアクションはログイン済みユーザーのみアクセス可能とし、indexアクションはログインしていなくてもアクセスできるようになります。

また、以下のように、exceptを使っても同じことが書けます。

class SampleController < ApplicationController
  before_action :authenticate_user!, except: [:index]

  def index
  end

  def show
  end
end

current_user

現在ログインしているユーザーを取得できます。

idを取得する際は、「current_user.id」で取得できます。

	
<%= link_to "プロフィール", user_path(current_user.id) %>

user_signed_in?

ビュー等でcurrrent_userを使うと、ログインしていない場合エラーになってしまうので、このメソッドを使って条件分岐します。

<% if user_signed_in? %>
    <%= render 'layouts/login_user_header' %>
<% else %>
    <%= render 'layouts/no_login_user_header' %>
<% end %>

user_session

ユーザーのセッション情報にアクセスできます。

参考サイト

https://qiita.com/tobita0000/items/866de191635e6d74e392
https://qiita.com/k4ssyi/items/3edcd0e5373a41677dee

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?