Подтвердить что ты не робот

Политики 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 допускает только два параметра. Есть ли способ решить эту проблему?

Спасибо!

4b9b3361

Ответ 1

Я нашел ответ на здесь.

Вот мой способ:

Добавьте функцию pundit_user в ApplicationController:

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