2

Working on an app where a User belongs_to an Organization. An Organization has_and_belongs_to_many Products, though an organizations_products table.

I want a User with a particular role to be able to manage Products for their Organization. In ability.rb:

def initialize(user)
  # ...snip unrelated stuff
  elsif user.is_manager?
    can :manage, Product, do |product|
      user.organization.products.include?(product)
    end

This describes what I want to do but it raises an exception in the products controller:

def index
    @products =  Product.accessible_by(current_ability)
end

because acessible_by can't be used with blocks in ability definitions. How can I write this ability in a way that is compatible with accessible_by?

4

1 回答 1

0
can :manage, Product, user.organization.products do |product|
  user.organization.products.include?(product)
end

澄清一下:CanCan 在 1.6 版中添加了第三个参数,您可以将其理解为 access_by 使用的范围。用于评估的块can :manage, @a_specific_product,如果您使用其中任何一个(范围或块),您可能应该同时使用两者。

另请参阅:这个问题,主要是这个问题的一个副本,以及文档

于 2013-08-28T18:07:38.387 回答