認可

ユーザーのロールによって使えるアクションを制限する。

pundit

pundit: 各アクションがどのユーザーに認可されているかをポリシーファイルで管理する
(cancancan: ユーザーごとにどのような権限を持っているかを管理する)

gem "pundit"
% bundle install
% rails g pundit:install

applicationコントローラでPunditをインクルード

class ApplicationController < ActionController::Base
  include Pundit
end

ポリシーファイルを編集

# app/policies/article_policy

class ArticlePolicy < ApplicationPolicy
  def create?
    user.admin? || user.general?
  end
  # falseが返ってくればcreateアクションは拒否されPundit::NotAuthorizedErrorが発生する
end
# app/controllers/articles_controller.rb

class ArticlesController < ApplicationController
  def created
    authorize @article # current_userと@articleをポリシーファイルの対応するメソッドに渡す
    # authorize Article インスタンスを利用しない(userの情報だけつかう)時に限り可能
    ...
  end
end

例外処理

# config/application.rb

config.action_dispatch.rescue_responses["Pundit::NotAuthorizedError"] = :forbidden
# HTTPステータスに割り当てる例外を設定する