2015-01-29 19 views
11

Jestem całkiem nowy z Rails i mam problem z następujących zasad (z wykorzystaniem Pundit): Chciałbym porównać dwa obiekty: @record i @foo, jak widać tutaj:pundit polityk z dwóch parametrów wejściowych

class BarPolicy < ApplicationPolicy 
    def show? 
    @record.foo_id == @foo 
    end 
end 

Nie sięgam, aby znaleźć dobry sposób na przekazanie drugiego parametru do metod poundit (@foo).

chciałbym zrobić coś takiego:

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

Ale metoda autoryzacji pozwala Pundit tylko dwa parametry. Czy istnieje sposób rozwiązania tego problemu?

Dzięki!

Odpowiedz

12

Znalazłem odpowiedź pod numerem here.

Oto mój sposób:

Dodaj pundit_user funkcję w ApplicationController:

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

Tworzenie klasy CurrentContext:

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

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

Aktualizacja metody initialize Pundit.

class ApplicationPolicy 
    attr_reader :user, :record, :foo 

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

Tak [to jest (https://github.com/elabs/pundit#additional-context) prawidłowy sposób udokumentowania. –