0

我在使用 cancan 限制显示给特定用户组的数据时遇到问题。

我的用户有很多产品。并且产品有很多优惠券。

在我的 routes.rb 我有这个:

resources :products do
  resources :vouchers
end

在能力.rb 中:

 can [:create, :update, :read ], Voucher, :product => { :user_id => user.id }

在我的凭证控制器中:

  def index
  ...
   if params[:product_id]
     @voucher = Voucher.find_all_by_product_id(params[:product_id])
   end
  ...
  end

最后,在我看来,我试图在与当前用户关联的产品组中显示优惠券列表。

例如:

  http://localhost:3000/products/eef4e33116a7db/voucher

这列出了产品组中的优惠券,但是,所有用户都可以看到每个优惠券/产品。

我会假设我的能力是错误​​的。请帮忙 :)

4

2 回答 2

0

对于遇到此问题的其他人,我需要在我的凭证控制器中执行以下操作:

 @product = Product.accessible_by(current_ability).find(params[:product_id])
 @voucher = @product.vouchers

然而,尽管这确实阻止了其他用户查看结果,但首先使用 access_by 加载产品会导致异常,需要单独的救援块。

于 2012-06-30T13:23:14.060 回答
0

查看 can can wiki 以获取记录:https ://github.com/ryanb/cancan/wiki/Fetching-Records

如果您正在调用load_and_authorize_resource,您将能够执行类似于以下两件事之一的操作:

  def index
  ...
   if params[:product_id]
     @vouchers = @vouchers.where(product_id: params[:product_id])
   end
  ...
  end

load_and_authorize_resource应该根据该控制器操作的参数自动分配@vouchers实例变量。accessible_by如果这不起作用,只需更明确地定义它:

if params[:product_id]
  @vouchers = Voucher.includes(:product).where(product_id: params[:product_id]).where(product: { user_id: current_user.id })
end
于 2012-06-29T14:55:34.783 回答