Search code examples
ruby-on-railspundit

Pundit with namespaced controllers


The policy_scope works perfectly finding the correct policy named Admin::RemittancePolicy but authorize method not.

module Admin
  class RemittancesController < AdminController # :nodoc:
    ...

    def index
      @remittances = policy_scope(Remittance).all

      render json: @remittances
    end

    def show
      authorize @remittance

      render json: @remittance
    end

    ...
  end
end

Take a look at output error:

"#<Pundit::NotDefinedError: unable to find scope `RemittancePolicy::Scope` for `Remittance(...)`>"

Perhaps a error with pundit, I really not know how fix it. Thanks.


More information below:

# policies/admin/admin_policy.rb
module Admin
  class AdminPolicy < ApplicationPolicy # :nodoc:
    def initialize(user, record)
      @user = user
      @record = record.is_a?(Array) ? record.last : record
    end

    def scope
      Pundit.policy_scope! user, record.class
    end

    class Scope # :nodoc:
      attr_reader :user, :scope

      def initialize(user, scope)
        @user = user
        @scope = scope.is_a?(Array) ? scope.last : scope
      end

      def resolve
        scope
      end
    end
  end
end

# controllers/admin/admin_controller.rb
module Admin
  class AdminController < ActionController::API # :nodoc:
    include Knock::Authenticable
    include Pundit

    before_action :authenticate_user

    after_action :verify_authorized, except: :index
    after_action :verify_policy_scoped, only: :index

    # def policy_scope!(user, scope)
    #   model = scope.is_a?(Array) ? scope.last : scope
    #   PolicyFinder.new(scope).scope!.new(user, model).resolve
    # end

    def policy_scope(scope)
      super [:admin, scope]
    end

    def authorize(record, query = nil)
      super [:admin, record], query
    end
  end
end

Solution

  • Your stacktrace says the error comes from

    app/policies/admin/admin_policy.rb:9:in 'scope'
    

    That's this:

    def scope
      Pundit.policy_scope! user, record.class
    end
    

    record.class evaluates to Remittance, so if I understand what you're trying to do, you need to change scope to

    def scope
      Pundit.policy_scope! user, [:admin, record.class]
    end