current_userでログイン中のUserを取れるとする。
Userはrole的なものを持っており、この値によってアクションへのアクセスの可否を決定したい。
たとえばこんな感じ
class User enum role: { general: 0, admin: 1, guest: 2 } end
ApplicationController
にサブクラスから利用するクラスメソッドを定義する
class ApplicationController < ActionController::Base def self.require_permission(permitted_roles, options = {}) before_action lambda { return if permitted_roles.include?(current_user.role) render 'errors/forbidden', status: 403 }, **options end end
サブクラスからはこう使う
PostsController < ApplicationController require_permission %w[general admin], only: %i[new create edit update] # 以下略 end
before_action
で使えるオプションは使えるので、いつものノリでアクションを指定できるのが嬉しい。