You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pundit中通过CurrentContext正确访问@user与@shop实现权限策略?

问题解决方法

问题根源

你定义的pundit_user返回的是CurrentContext实例,而非直接的User对象,但ContactPolicy初始化方法错误地把这个上下文实例当成User来使用;后续修改初始化时又直接引用未定义的user和shop变量,导致权限判断失败。

正确修改步骤

  1. 给CurrentContext添加属性读取器
    首先要让CurrentContext能对外暴露内部的user和shop实例,给它加上attr_reader:
class CurrentContext
  attr_reader :user, :shop

  def initialize(user, shop)
    @user = user
    @shop = shop
  end
end
  1. 修正ContactPolicy的初始化方法
    Policy的第一个参数是CurrentContext实例,需要从这个实例里提取user和shop:
def initialize(current_context, contact)
  @user = current_context.user
  @shop = current_context.shop
  @contact = contact
end
  1. 正常使用权限判断逻辑
    现在@user就是真实的User对象,可以正常调用它的属性和方法了:
def create?
  @user && (@user.admin? || @user.editor? || (@user.id == @contact.user_id))
end

这样就能正确访问@user和@shop的值,实现预期的权限控制逻辑。

内容的提问来源于stack exchange,提问作者Jerome

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 05:54:17