Rails / Cancan - 通过关联加载资源

时间:2018-01-15 20:06:44

标签: ruby-on-rails cancan cancancan

我有这些模特:

Company 
  has_many :users
  has_many :accounts

User
  belongs_to :company

Account
  belongs_to :company

用户应该可以通过他们的公司访问某些资源,并且我想隐式加载那些使用Cancan的资源:

class AccountsController < ApplicationController
  load_resource # Cancan doesn't know how to load through the user's company

我显然可以明确地这样做:

class AccountsController
  def index
    @accounts = current_user.company.accounts
  end

但这似乎是不必要的代码,我怀疑它已经是一种模式。

我看到Cancan能够在当前用户上定义through

class AccountsController
  load_resource through: :current_user

但这会调用current_user.accounts - 这是无效的,因为帐户属于公司,而不属于用户。我可以将accounts来电从用户推迟到公司,但这看起来像是黑客。

我也试过传递一个字符串:

class AccountsController
  load_resource through: 'current_user.company'

这给了我'@current_user.company' is not allowed as an instance variable name

我做了一些谷歌搜索,但无法找到它。有什么帮助吗?

1 个答案:

答案 0 :(得分:4)

尝试这样的事情:

class AccountsController
  load_resource :company, through: :current_user, singleton: true
  load_resource through: :company
end

在您的示例中,我相信您已经在@accounts = current_user.company.accounts中拥有此功能。使用cancan的load_resource加载公司,该帐户应该会产生一组类似的查询。

相关问题