[英]Cancan Ability Issue with Inheritance
I'm having problems restricting the data shown to a specific user group using cancan.. 我在使用cancan将显示的数据限制到特定用户组时遇到问题。
My Users have many Products. 我的用户有很多产品。 And Products have many Vouchers. 并且产品有很多凭证。
In my routes.rb I have this: 在我的routes.rb中,我有这个:
resources :products do
resources :vouchers
end
In ability.rb: 在Capacity.rb中:
can [:create, :update, :read ], Voucher, :product => { :user_id => user.id }
And in my Voucher controller: 在我的Voucher控制器中:
def index
...
if params[:product_id]
@voucher = Voucher.find_all_by_product_id(params[:product_id])
end
...
end
Finally, in my view, I'm trying to display a list of vouchers in a Product group associated with current user. 最后,在我看来,我试图显示与当前用户相关联的“产品”组中的代金券列表。
For example: 例如:
http://localhost:3000/products/eef4e33116a7db/voucher
This lists the vouchers in the product group however, ALL users can see every voucher / product.. 这列出了产品组中的代金券,但是,所有用户都可以看到每个代金券/产品。
I'll assume my abilities are wrong. 我认为我的能力是错误的。 Help please :) 请帮助 :)
Have a look at the can can wiki for fetching records: https://github.com/ryanb/cancan/wiki/Fetching-Records 看看用于获取记录的can can wiki: https : //github.com/ryanb/cancan/wiki/Fetching-Records
If you're calling load_and_authorize_resource
, you'll either be able to do something similar to one of these two things: 如果要调用load_and_authorize_resource
,则可以执行与以下两项操作之一相似的操作:
def index
...
if params[:product_id]
@vouchers = @vouchers.where(product_id: params[:product_id])
end
...
end
load_and_authorize_resource
should automatically assign the @vouchers
instance variable based on the accessible_by
parameters for that controller action. load_and_authorize_resource
应该基于该控制器操作的accessible_by
参数自动分配@vouchers
实例变量。 If this isn't working, just define it more explicitly: 如果这不起作用,则可以更明确地定义它:
if params[:product_id]
@vouchers = Voucher.includes(:product).where(product_id: params[:product_id]).where(product: { user_id: current_user.id })
end
For anyone else having this issue, I needed to do the following in my vouchers controller: 对于其他遇到此问题的人,我需要在我的代金券控制器中执行以下操作:
@product = Product.accessible_by(current_ability).find(params[:product_id])
@voucher = @product.vouchers
However, although this did actually block other users from viewing the results, loading the product first with accessible_by led to an exception which required a separate rescue block. 但是,尽管这实际上确实阻止了其他用户查看结果,但是首先使用accessible_by加载产品会导致异常,因此需要单独的救援块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.