LoginSignup
935
992

More than 5 years have passed since last update.

Rails deviseで使えるようになるヘルパーメソッド一覧

Last updated at Posted at 2017-05-07

毎回使いたくなるたびに調べ直しているので個人的な備忘録がてらまとめておきます。

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

※モデル名にUser以外を使用している場合、それぞれのメソッドの『user』部分を書き換える
ex.モデル名がmemberの場合、

  • before_action :authenticate_member!
  • member_signed_in?
  • current_member
  • member_session

before_action :authenticate_member!
となる。

以下に各メソッドの補足を書いていきます。

before_action :authenticate_user!

コントローラーの先頭に記載することで、そこで行われる処理はログインユーザーによってのみ実行可能となります。
下記の通り記載した場合、記事の一覧、詳細を確認することができるのはログインユーザーのみとなります。

class ArticlesController < ApplicationController
  before_action :authenticate_user!

  def index
  end

  def show
  end
end

下記のように記載し、一覧(index)は未ログインユーザーでも実行可能・詳細(show)はログインユーザーのみ実行可能とすることも可能です。

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

  def index
  end

  def show
  end
end

user_signed_in?

before_action :authenticate_user!よりも細かい分岐でログイン/未ログインの処理を分岐することができます。
コントローラー、ビュー問わず使用できます。

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

  def index
    flash[:notice] = "ログイン済ユーザーのみ記事の詳細を確認できます" unless user_signed_in?
  end

  def show
  end
end
...
<body>
  ...
  <% if user_signed_in? %>
    <%= render 'layouts/login_user_header' %>
  <% else %>
    <%= render 'layouts/no_login_user_header' %>
  <% end %>
  ...
</body>
...

自分はログイン状態によってレイアウトを分けるときによく使っています。

current_user

一番利用頻度が高いかも。
現在ログインしているユーザーをモデルオブジェクトとして利用できます。
関連付けがされている場合、子要素・親要素の取得などが可能です。

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

  def index
    flash[:notice] = "ログイン済ユーザーのみ記事の詳細を確認できます" unless user_signed_in?
  end

  def show
  end

  def new
    @article= current_user.articles.build
  end
end

ユーザーのメールアドレスを表示したい場合

...
<div>あなたのメールアドレス:<%= current_user.email %></div>
...

user_session

ユーザーのセッション情報を設定・取得することができます。
下記コードはdeviseのサンプルコードより参照しました。
有効期限の設定やDBに保存するほどではないステータスの保持に使う感じでしょうか。
恥ずかしながら実際に開発で使用したことがありませんので、お詳しい方補足いただければ幸いです。

class ArticlesController < ApplicationController
...
  def index
    user_session[:cart] = "Cart"
    respond_with(current_user)
  end
...
  def expire
    user_session['last_request_at'] = 31.minutes.ago.utc
...
  end
...
end

まとめ

説明の不備・不足等ございましたら、ご指摘いただけますと助かります。

935
992
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
935
992