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

kid*_*rew 2 ruby-on-rails cancan cancancan

我有以下模型:

Company 
  has_many :users
  has_many :accounts

User
  belongs_to :company

Account
  belongs_to :company
Run Code Online (Sandbox Code Playgroud)

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

class AccountsController < ApplicationController
  load_resource # Cancan doesn't know how to load through the user's company
Run Code Online (Sandbox Code Playgroud)

我显然可以明确地做到这一点:

class AccountsController
  def index
    @accounts = current_user.company.accounts
  end
Run Code Online (Sandbox Code Playgroud)

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

我看到Cancan可以through在当前用户上定义一个:

class AccountsController
  load_resource through: :current_user
Run Code Online (Sandbox Code Playgroud)

但这会打电话给您current_user.accounts-这是无效的,因为帐户属于公司,而不是用户。我可以将accounts呼叫从User(用户)转移到Company(公司),但这似乎很容易。

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

class AccountsController
  load_resource through: 'current_user.company'
Run Code Online (Sandbox Code Playgroud)

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

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

Der*_*per 5

尝试这样的事情:

class AccountsController
  load_resource :company, through: :current_user, singleton: true
  load_resource through: :company
end
Run Code Online (Sandbox Code Playgroud)

在您的示例中,我相信您已经在中@accounts = current_user.company.accounts。使用cancan's load_resource加载公司,然后该帐户将产生一组类似的查询。