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

标签 ruby-on-rails ruby-on-rails-4 pundit policies

我对 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/

相关文章:

ruby-on-rails - 设置 :null => false as default behaviour when creating a table migration

javascript - 为什么我的 Rails Controller 操作中需要 `render layout: false`?

javascript - 如何禁用 twitter bootstrap 电子邮件验证弹出窗口?

ruby-on-rails-4 - Rails 4 上的数据表 ruby

ruby-on-rails - 不同的模型如何在 Rails 中使用相同的登录页面

ruby-on-rails - 使用 Pundit in Rails 限制整个 Controller 的 DRY 方法是什么?

ruby-on-rails - 无法通过 Pundit gem 完成新 Controller 操作

ruby-on-rails - Rails 4 .order() 被 JOINS 破坏

jquery - Ruby 1.9.1、Rails 2.3.2 和 jrails 0.4 出现 "rescue in const_missing"错误

ruby-on-rails - 是否可以在 Ruby 中对默认参数值进行动态方法调用?