LoginSignup
3
0

authenticate_user!について(Rails)

Posted at

ポートフォリオ制作でauthenticate_user!を使用した為、アウトプットします。

authenticate_user!とは?
authenticate_user!の使い方(例)
オプション(補足)

authenticate_user!とは?

  • ユーザーの認証(ログイン)を確認するためのもの。
  • deviseのメソッドである。
  • コントローラ上で定義するものである。

以下にauthenticate_user!の使用例を記載します。

authenticate_user!の使用例(その1)

XXX_controller.rb
before_action :authenticate_user!

基本的にはbefore_actionと合わせて使用します。
controller.rbの最上部に記述することで
全てのアクションの前に、ユーザーがログインしているかどうか確認する。

authenticate_user!の使用例(その2)

XXX_controller.rb
before_action :authenticate_user!, only: [:index, :show]

only:は特定のアクションにのみ処理を実行したい時に使用します。
その2ではindexとshowにのみ適応させています。
indexとshowのみに適用したい場合は、only: [:index, :show]をつける。
その他にもオプションがあるので適切なものを選んでください。

オプション(補足)

オプションを使用することで様々な条件下で使用出来る。

内容 意味
only 実行するアクション
except 実行しないアクション 
if 実行する条件 
unless 実行しない条件
3
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
3
0