2016-01-17 27 views
0

我正在與cancancan和設計的Rails應用程序。我有一個控制器,它根據HTTP方法打算使用的模型接收三個不同的請求(它是一個基於REST的控制器)。此控制器管理產品模型,OrderProducts模型和BusinessProducts模型。我在每個RESTFUL方法上使用if語句來處理這個問題,如下所示。我的問題是,是否有一種方法可以爲使用Cancancan的ProductController的每個操作中的每個模型定義授權?如您所知,能力類允許我授權產品模型,但是,由於我們在同一控制器中涉及更多案例,因此我們無法使用產品模型的能力類中定義的相同規則處理所有這些案例。預先感謝您的幫助!Rails,Cancancan,Devise,作者

PARAMS [:order_product],而params [:business_products]是其在配置中定義的標誌/ 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 

回答

2

如果你想在一個控制器動作使用條件許可,我會建議做而不是使用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

+0

非常感謝肖恩,它解決了我的問題! –

+0

太棒了!你能接受我的回答嗎? –