【问题标题】:Writing a Rails cancan ability using an association, that works with accessible_by使用关联编写 Rails cancan 功能,可与 access_by 一起使用
【发布时间】:2013-02-17 08:52:41
【问题描述】:

User 属于Organization 的应用程序上工作。 Organization has_and_belongs_to_many Products,虽然是 organizations_products 表。

我想要一个具有特定角色的User 能够为他们的Organization 管理产品。在ability.rb:

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

这描述了我想要做什么,但它在产品控制器中引发了一个异常:

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

因为acessible_by can't be used with blocks 在能力定义中。如何以兼容accessible_by的方式编写此功能?

【问题讨论】:

    标签: ruby-on-rails-3 cancan


    【解决方案1】:
    can :manage, Product, user.organization.products do |product|
      user.organization.products.include?(product)
    end
    

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

    另请参阅:this question,这主要是这个的副本,以及 the docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多