0
votes

Here is my problem. I have multiple users with multiple subscriptions each and i want to authorise subscriptions index method with Pundit. My routes.rb:

resources :users do
   resources : subscriptions
end

Lets assume i'm user with id 1. What i need is to get list of subscriptions when i open /users/1/subscriptions and Pundit access error when i open /user/2/subscriptions

Here is my subscriptions_controller.rb

SubscriptionController < ApplicationController
    def index
        @user = User.find(params[:user_id])
        @subscriptions = @user.subscriptions

        authorize @subscriptions
    end
end

I can do authorize @user, :subscriptions_index, but it just feels wrong to write user policy for subscription authentication. How should i approach this problem? Thanks in advance.

1

1 Answers

0
votes

This should work for you (might not be the most efficient):

class SubscriptionController < ApplicationController
  def index
    @user = User.find(params[:user_id])
    # this should either return the same or an empty association
    @subscriptions = @user.subscriptions
    authorize @subscriptions
  end
end

class SubscriptionPolicy < ApplicationPolicy
  def index?
    # asking if all subscriptions have the current_user id as the user_id
    record.all? {|sub| sub.user_id == user.id }         
  end
end