0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

学習66日目

Posted at

内容

deviseで使えるヘルパーメソッドまとめ

前提

ruby on railsでdeviseを用いたユーザー認証実装中

説明

current_user

現在ログインしているユーザーのインスタンスを返す。
(例)

# 現在ログインしているユーザーのnameを取得
# (usersテーブルにnameカラムがある前提)
current_user.name

# 現在ログインしているユーザーに紐付くtweetを取得
# (ユーザーとツイートが1対多のアソシエーションで結ばれている前提)
current_user.tweets

user_signed_in?

ユーザーがログインしている場合はtrue、していない場合はfalseを返す。
(例)

<% if user_signed_in? %>
  ログアウト
<% else %>
  ログイン
<% end %>

上記のように、ログイン中かどうかで表示を分けたい時に使うことが多い。

authenticate_user!

ユーザーがログインしていない場合は、ログイン画面にリダイレクトさせる。

(例)

before_action :authenticate_user!

上記のように、特定のコントローラにおいてログイン時以外の使用を制限できる。

特定のアクションだけに対して制限することも可能。

(例)

before_action :authenticate_user!, only: [:edit, :update]

コメント

ビューだけでなくコントローラからも漏れなく適切に制御する必要がある。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?