LoginSignup
44
37

More than 5 years have passed since last update.

before_action :authenticate_user!をコントローラごとに書かない方法

Posted at

authenticate_user!とは

authenticate_user!はdeviseを入れると使えるようになるヘルパーの一つ。
コントローラーに設定して、ログイン済ユーザーのみにアクセスを許可する。

ただしこれを全てのコントローラごとに設定するのは、見栄えが悪い。

なので継承を使って修正していく。

ディレクトリを作ってその中にapplication.controller.rbを作る

例えばbefore_action :authenticate_user!を通常のcontroller/application_controller.rbに書いてしまうと、
全コントローラに適用されて(homeとかtopとか)、ログインが関係ないところにも実行されてしまう。

なので、例えばusersディレクトリを作り、その中にapplication_controller.rbを作る。

users/application_controller.rb
Class Users::ApplicationController  < ApplicationController
end

クラス名はディレクトリ構造を揃えないといけないので
 Users::ApplicationControllerとなる。(usersディレクトリの中のapplication_controllerってこと)
で、下記のようにbefore_action :authenticate_user!を入れる。

user/application_controller.rb
Class Users::ApplicationController  < ApplicationController
before_action :authenticate_user!
end

継承元を変える

次に、もともとbefore_action :authenticate_user!を使用していたusers_controller.rbの継承元を変更する

users_controller.rb
class UserController < ApplicationController

これを下記のように変更する。

users_controller.rb
class UserController < User::ApplicationController

このようにして継承先をUser::ApplicationControllerに変更することで、
before_action :authenticate_user!が実行されるようになる(homeとかtopとかには実行されずに済む)

44
37
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
44
37