Rails, Cancancan, Devise, 作者

Rails, Cancancan, Devise, author

我正在使用 cancancan 和 devise 开发 Rails 应用程序。我有一个控制器,它根据 HTTP 方法要使用的模型接收三个不同的请愿书(它是一个基于 RESTful 的控制器)中包含的任何操作。该控制器管理 Product 模型、OrderProducts 模型和 BusinessProducts 模型。我在每个 RESTFUL 方法上使用 if 语句来处理这个问题,如下所示。我的问题是,有没有办法使用 Cancancan 为这个 ProductController 的每个动作中的每个模型定义授权?

如您所知,能力class允许我对产品模型进行授权,但是,由于我们在同一控制器中涉及的案例较多,因此我们无法使用能力[中定义的相同规则来处理所有案例class为产品型号。非常感谢您的帮助!!!

params[:order_product] 和 params[:business_products] 是在 config/routes.rb

中定义的标志
products_controller.rb

class ProductsController < ApplicationController

load_and_authorize_resource

def index
if params[:order_product]
  @order = Order.find(params[:order_id])
  @order.products.reload
  render json: @order.products.with_price

elsif params[:business_product]
  @business = Business.find(params[:business_id])
  @business.products.reload
  render json: @business.products.with_price
else
  render json: @products
end
end

如果您想在控制器操作中使用条件授权,我建议您手动执行而不是使用 load_and_authorize_resource。例如:

class ProductsController < ApplicationController

  def index
    if params[:order_product]
      @order = Order.find(params[:order_id])
      authorize! :read, @order
      @order.products.reload
      render json: @order.products.with_price
    elsif params[:business_product]
      @business = Business.find(params[:business_id])
      authorize! :read, @business
      @business.products.reload
      render json: @business.products.with_price
    else
      authorize! :read, Product
      render json: @products
    end
  end

end

参考:https://github.com/ryanb/cancan/wiki/authorizing-controller-actions