【问题标题】:Rails, Cancancan, Devise, authorRails, Cancancan, 设计, 作者
【发布时间】:2016-01-17 03:01:03
【问题描述】:

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

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

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

【问题讨论】:

    标签: ruby-on-rails-4 devise cancancan


    【解决方案1】:

    如果您想在控制器操作中使用条件授权,我建议您手动进行而不是使用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

    【讨论】:

      猜你喜欢
      • 2015-12-12
      • 1970-01-01
      • 2014-06-16
      • 1970-01-01
      • 2015-11-27
      • 1970-01-01
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      相关资源
      最近更新 更多