Search code examples
ruby-on-railsauthorizationpundit

How do I authorize a controller action with Pundit if authorization depends on an instance variable?


I have an wedding class with many organizers, and the resources are nested so, to view an event's organizers, I have to access: /events/23/organizers

The index controller for organizers is like so:

Class OrganizersController < ApplicationController
  def index
    @wedding = Wedding.find(params[:wedding_id]
    @organizers = Organizer.where(wedding: @wedding)
  end
end

Trouble is, how do I allow pundit to authorize the index action for OrganizersController and only if for the @wedding in the instance, @wedding.organizers.find(user: current_user).present??

They're two entirely different models, and the authorization of one depends on other.


Solution

  • Closest I've come to an answer is this.

    The way I usually do it, is to add a list_organizers? predicate to the wedding policy and then:

    authorize(@wedding, :list_organizers?)
    

    It's not terribly elegant though.

    If you find a better way to do this, please answer and I'll accept it as the better one.