1

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.

kabukiman
  • 185
  • 14

1 Answers1

0

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
nikkon226
  • 998
  • 6
  • 11
  • Thanks for suggestion but as you pointed out it's not most efficient – kabukiman May 21 '15 at 22:53
  • If you are looking for the most efficient, then you should amend your question to ask for that. – nikkon226 May 21 '15 at 22:55
  • @nikkon226 What if a user has no subscriptions? Doesn't this policy allow you through to the path in that case? – s_dolan Jun 29 '15 at 17:26
  • You could call the policy directly with a nil value inside a raise. It's described further down [this section](https://github.com/elabs/pundit/blob/master/README.md#policies) of the Pundit documentation. – nikkon226 Jun 29 '15 at 20:42