Search code examples
ruby-on-railspundit

Rails 5, pundit authorization


Pundit works well, if action has resources like:

class Admin::PagesController << ApplicationController
  def index
    @pages = Page.all
  end
end

How to authorise method without any resources in action?

class Admin::DashboardController << ApplicationController
  def index
  end
end

I hav file policies/admin/dashboard_policy.rb

class Admin::DashboardPolicy < ApplicationPolicy
  class Scope < Scope
    def resolve
      scope.all
    end
  end
end

This file was generated by command:

rails g pundit:policy Admin/Dashboard

File views/admin/index.html.slim has only static text. Nothing more.

How to authorise action without any resources?

Regards Sssebaaa


Solution

  • To authorize without a scope or model instance call authorize with a symbol or array of symbols (when namespaced):

    class Admin::DashboardController << ApplicationController
      def index
        authorize [:admin, :dashboard]
      end
    end
    

    This will call the #index? method on the policy class:

    class Admin::DashboardPolicy < ApplicationPolicy
      def index?
        user.admin?
      end
    end
    

    You can also remove the scope completely from your policy.