如何使用 Pundit 为两个控制器设置授权策略?

How to set up authorization policies for two controllers using Pundit?

我正在使用 RailsApps Pundit Tutorial 学习 Pundit,教程中的这句话让我很困惑:

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. 如何创建一个策略(o 组策略)以允许具有 "role_a" 的用户使用 users_controller.index 操作并允许具有 "role_b" 的用户使用 orders_controller.index 操作?

    1.1 这是否需要两个不同的策略(UserPolicy 和 OrderPolicy),或者我应该为每个控制器以不同的方式命名索引操作以在 UserPolicy 上区分它?

是的,它需要两个不同的策略(UserPolicyOrderPolicy )

#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

并且在 users_controller

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

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

并且在您的 index 方法中 orders_controller

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