多级嵌套关联快捷方式

Multi level nested association shortcuts

我在联想方面遇到了麻烦。基本上,用户有组(不与任何人共享)。每个小组都有客户、项目和任务。

我应该定义如下内容:

class User < ActiveRecord::Base 
  has_many :groups 
  has_many :clients, through: :groups
  has_many :projects, through :clients #(could be groups?) 
  has_many :task, through :groups 
end

这是正确的做法吗?我只想从每个用户那里列出他们所有的任务、组和客户。这样'travel'通过模型可以吗? 我遵循了一些 RoR 教程和书籍,但它们都涉及较少的模型。

basic rough model

您可以根据需要在 中导航。 Here 解释了当您想要通过嵌套 has_many 关联的 快捷方式 时的情况(在我发布的 link 下面搜索)。

鉴于此解释,要使其正常工作,您需要执行以下操作(您已接近完成):

class User < ActiveRecord::Base
  has_many :groups 
  has_many :clients, through: :groups
  has_many :projects, through :groups
  has_many :tasks, through :groups 
end

class Group < ActiveRecord::Base
  belongs_to :user

  has_many :clients
  has_many :projects, through :clients
  has_many :tasks, through :clients 
end

class Client < ActiveRecord::Base
  belongs_to :group

  has_many :projects
  has_many :tasks, through :projects 
end

class Project < ActiveRecord::Base
  belongs_to :client

  has_many :tasks
end

class Task < ActiveRecord::Base
  belongs_to :project
end

设置此设置的另一种方法(可能更短)是(查看 here 记录两种策略的位置):

class User < ActiveRecord::Base
  has_many :groups 
  has_many :clients, through: :groups
  has_many :projects, through :clients
  has_many :tasks, through :projects 
end

class Group < ActiveRecord::Base
  belongs_to :user

  has_many :clients
end

class Client < ActiveRecord::Base
  belongs_to :group

  has_many :projects
end

class Project < ActiveRecord::Base
  belongs_to :client

  has_many :tasks
end

class Task < ActiveRecord::Base
  belongs_to :project
end

希望对您有所帮助!