【发布时间】: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::RemittancePolicy。authorize将转到RemittancePolicy。
标签: ruby-on-rails pundit