ruby-on-rails-4 - 如何使用 Pundit 为两个 Controller 设置授权策略?

标签 ruby-on-rails-4 pundit railsapps

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

    1.1 这是否需要两个不同的策略(UserPolicy 和 OrderPolicy),或者我应该为每个 Controller 命名不同的索引操作以在 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_controllerindex 方法中

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_controllerindex 方法中

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

关于ruby-on-rails-4 - 如何使用 Pundit 为两个 Controller 设置授权策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31666719/

相关文章:

git - 为多个环境 fork 我现有的 heroku 应用程序

ruby-on-rails - 如果 Rails 中的字段为空,如何替换组/总和中的字段

ruby-on-rails - Rails 4 - Pundit - 如何编写范围

railsapps - 无法启动 Rails 服务器 - 未初始化的常量 Sprockets::Rails::VERSION::(NameError)

ruby-on-rails - 从表单中选择枚举以设置角色

html - Ruby JSON 多词字符串在 HTML 中呈现不正确

mysql - ActiveRecord 十进制类型字段截断为整数

ruby-on-rails - Pundit 策略错误未定义方法 `image' 为 nil :NilClass

ruby-on-rails - 不同的模型如何在 Rails 中使用相同的登录页面

ruby-on-rails - 无法安装 rails - "File exists @ dir_s_mkdir"错误