我对 Rails 很陌生,但我对以下策略有疑问(使用 Pundit ):我想比较两个对象:@record
和 @foo
,正如你在这里看到的:
class BarPolicy < ApplicationPolicy
def show?
@record.foo_id == @foo
end
end
我没有找到将第二个参数传递给专家方法 (@foo) 的好方法。
我想做类似的事情:
class BarsController < ApplicationController
def test
authorize bar, @foo, :show? # Throws ArgumentError
...
end
end
但是 Pundit 授权方法只允许两个参数。
有没有办法解决这个问题?
谢谢!
最佳答案
我在 here 找到了答案.
这是我的方法:
添加 pundit_user
函数在 ApplicationController
:
class ApplicationController < ActionController::Base
include Pundit
def pundit_user
CurrentContext.new(current_user, foo)
end
创建
CurrentContext
类(class):/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
关于ruby-on-rails - 具有两个输入参数的 Pundit 策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28216678/