2

I'm learning Pundit using the RailsApps Pundit Tutorial and this statement from the tutorial totally confused me:

Given that the policy object is named UserPolicy, and we will use it for authorization from the Users controller, you might wrongly assume that the name of the policy object will always match the name of the controller. That is not the case.

  1. How can I create a policy (o set of policies) that allow users with the "role_a" to use the users_controller.index action and users with the "role_b" to use the orders_controller.index action?

    1.1 Does this require two different policies (UserPolicy and OrderPolicy) or should I name the index action for every controller differently to differentiate it on the UserPolicy?

Daniel Kehoe
  • 10,952
  • 6
  • 63
  • 82

1 Answers1

2

Yes it requires two different policies(UserPolicy and OrderPolicy)

#user_policy.rb
class UserPolicy
attr_reader :current_user

  def initialize(current_user)
    @current_user = current_user
  end

  def index?
    @current_user.role_a?
  end
end

And in your index method of users_controller

def index
  @user = User.find(params[:id])
  authorize @user
end

Same for OrderPolicy

#order_policy.rb
class OrderPolicy
attr_reader :current_user

  def initialize(current_user)
    @current_user = current_user
  end

  def index?
    @current_user.role_b?
  end
end

And in your index method of orders_controller

def index
  @user = User.find(params[:id])
  authorize @user
end
Pavan
  • 33,316
  • 7
  • 50
  • 76