我正在开发一个带有cancancan的Rails应用程序。我有一个控制器,根据HTTP方法要使用的模型,它接收三种不同的请求,请求它包含的任何操作(它是一个基于RESTful的控制器)。该控制器管理产品模型、OrderProducts模型和BusinessProducts模型。我在每个RESTFUL方法上使用if语句来处理这个问题,如下所示。我的问题是,是否有一种方法可以使用Cancancan为该ProductController的每个操作定义每个模型的授权?
如您所知,cannot类允许我对产品模型进行授权,但是,由于在同一个控制器中涉及更多的情况,所以我们不能使用产品模型的cannot类中定义的相同规则来处理它们。提前感谢您的帮助!
params:order_product和params:business_products是配置/params:business_products中定义的标志
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发布于 2016-01-17 04:29:15
如果您想在控制器操作中使用条件授权,我建议您手动执行,而不是使用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
https://stackoverflow.com/questions/34834644
复制相似问题