ruby-on-rails – 具有两个输入参数的Pundit策略

我和Rails很新,我对以下政策有问题(使用 Pundit):我想比较两个对象:@record和@foo,如下所示:
class BarPolicy < ApplicationPolicy
  def show?
    @record.foo_id == @foo
  end
end

我找不到找到一个很好的方法来传递第二个参数到pundit方法(@foo).

我想做一些像:

class BarsController < ApplicationController
  def test
    authorize bar,@foo,:show? # Throws ArgumentError
    ...
  end
end

但是Pundit授权方法只允许两个参数.
有办法解决这个问题吗?

谢谢!

解决方法

我在 here找到了答案.

这是我的方式:

在ApplicationController中添加pundit_user函数:

class ApplicationController < ActionController::Base
include Pundit
def pundit_user
    CurrentContext.new(current_user,foo)
end

创建CurrentContext类:

/lib/pundit/current_context.rb
class CurrentContext
  attr_reader :user,:foo

  def initialize(user,foo)
    @user = user
    @foo = foo
  end
end

更新初始化Pundit方法.

class ApplicationPolicy
  attr_reader :user,:record,:foo

  def initialize(context,record)
    @user = context.user
    @foo = context.foo
    @record = record
  end
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...