多级嵌套关联快捷方式

时间:2016-04-16 00:41:41

标签: ruby-on-rails associations models model-associations

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

我应该定义类似的内容:

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

这是正确的做法吗?我只想从每个用户列出他们的所有任务,组和客户。旅行&#39;是否可以。通过这样的模特?  我已经阅读了一些RoR教程和书籍,但所有这些都涉及的模型较少。

basic rough model

1 个答案:

答案 0 :(得分:1)

您可以按照自己的意愿导航。如果您希望快捷方式通过嵌套has_many关联(在我发布的链接下方搜索一下),就会解释Here

所以给出这个解释,为了实现这个目的,你需要做以下事情(你接近它):

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

希望它有所帮助!