我是 Pundit 的撰稿人。默认情况下,策略只能访问当前用户和您正在检查权限的记录。
您可以使用Pundit 文档中定义的上下文模式 https://github.com/elabs/pundit#additional-context。首先在您的应用程序中创建一个用户上下文类app/model
在本例中,目录接受您需要的所有上下文参数session
.
class UserContext
attr_reader :user, :session
def initialize(user, session)
@user = user
@session = session
end
end
然后,您可以使用您的实例覆盖 pundit 使用的用户记录UserContext
class.
class ApplicationController
include Pundit
def pundit_user
UserContext.new(current_user, session)
end
end
最后让您的应用程序策略接受上下文。如果您想保持符合旧策略,请将这些方法委托给上下文。
class ApplicationPolicy
attr_reader :context, :user, :session
def initialize(context, record)
@context = context
@record = record
end
delegate :user, to: :context
delegate :session, to: :context
...
end
现在您可以访问session
在您的政策内。