I'm pretty new with Rails and I have a problem with the following policies (using Pundit): I'd like to compare two objects: @record
and @foo
, as you can see here:
class BarPolicy < ApplicationPolicy
def show?
@record.foo_id == @foo
end
end
I don't reach to find a good way to pass a second parameter to pundit methods (@foo).
I'd like to do something like:
class BarsController < ApplicationController
def test
authorize bar, @foo, :show? # Throws ArgumentError
...
end
end
But the Pundit authorize method allows only two parameters. Is there a way to solve this issue?
Thanks!
I found the answer at here.
Here is my way:
Add a pundit_user
function in ApplicationController
:
class ApplicationController < ActionController::Base
include Pundit
def pundit_user
CurrentContext.new(current_user, foo)
end
Create the CurrentContext
class:
/lib/pundit/current_context.rb
class CurrentContext
attr_reader :user, :foo
def initialize(user, foo)
@user = user
@foo = foo
end
end
Update the initialize Pundit method.
class ApplicationPolicy
attr_reader :user, :record, :foo
def initialize(context, record)
@user = context.user
@foo = context.foo
@record = record
end
end