【问题标题】:Pundit with namespaced controllers具有命名空间控制器的 Pundit
【发布时间】:2017-04-30 14:54:19
【问题描述】:

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

【问题讨论】:

  • show? 方法对于您的 Admin::RemittancePolicy 来说是什么样的?你说policy_scope 工作得很好,authorize 工作得很好,但我觉得你粘贴的错误不是直接来自你提供的任何代码。也显示完整的错误怎么样?
  • show 现在什么都不做。感谢尝试帮助我。完整的堆栈在这里gist.github.com/brunowego/c9ce9a709fcec94e0d313f32dbc645ae
  • 只有policy_scope 可以正确转到Admin::RemittancePolicyauthorize 将转到 RemittancePolicy

标签: ruby-on-rails pundit


【解决方案1】:

您的堆栈跟踪表明错误来自

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

【讨论】:

  • 正是我要找的,这么简单。谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-03-17
  • 2014-05-19
  • 2014-11-07
  • 2016-07-19
  • 2020-06-14
  • 1970-01-01
  • 2015-07-05
  • 2012-07-08
相关资源
最近更新 更多