LoginSignup
6
7

More than 3 years have passed since last update.

[rails]deviseのヘルパーメソッドbefore_action :authenticate_user!の使い方

Posted at

before_action :authenticate_user!について

deviseを簡単に説明すると、ログイン系をやってくれるgemです。

そのdeviseのヘルパーメソッドauthenticate_user!メソッドは、コントローラーにbefore_actionで記載することで、そのコントローラーで行われる処理はログインユーザーのみ実行可能とすることができるメソッドです。

before_action :authenticate_user!の使い方

authenticate_user!メソッドはコントローラーに記載します。

class PostsController < ApplicationController
  before_action :authenticate_user!

  def index
  end

end

このように記載するとposts_controllerでの処理をすることができるのはログインユーザーのみとなります。

一部の処理を未ログインユーザーでも行えるようにする

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

  def index
  end

  def show
  end

end

このように記載することで、showアクションのみを未ログインユーザーが使用できないようにできます。

間違いなどがありましたらご指摘いただければ幸いです。
最後までご覧いただきありがとうございました。

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