我正在使用 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.
如何创建一个策略(一组策略),允许具有“role_a”的用户使用 users_controller.index 操作,并允许具有“role_b”的用户使用orders_controller.index 操作?
1.1 这是否需要两个不同的策略(UserPolicy 和 OrderPolicy),或者我应该为每个 Controller 命名不同的索引操作以在 UserPolicy 上区分它?
最佳答案
是的,它需要两个不同的策略(UserPolicy 和 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
在 users_controller
的 index
方法中
def index
@user = User.find(params[:id])
authorize @user
end
订单策略相同
#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
在 orders_controller
的 index
方法中
def index
@user = User.find(params[:id])
authorize @user
end
关于ruby-on-rails-4 - 如何使用 Pundit 为两个 Controller 设置授权策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31666719/