Pundit 与命名空间控制器

Pundit with namespaced controllers

policy_scope 可以完美地找到名为 Admin::RemittancePolicy 的正确策略,但 authorize 方法不能。

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

看看输出错误:

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

可能是专家的错误,我真的不知道如何解决。谢谢。


更多信息如下:

# 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

您的堆栈跟踪显示错误来自

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

就是这个:

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

record.class 的计算结果为 Remittance,因此如果我理解您要执行的操作,您需要将 scope 更改为

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