我在关联方面遇到了问题。基本上,用户有组(不与任何人共享)。每个小组都有客户、项目和任务。
我应该定义这样的东西吗:
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
这样做正确吗?我只想从每个用户中列出他们所有的任务、组和客户端。像这样"穿越"模型可以吗?我学习了一些RoR教程和书籍,但它们都涉及较少的模型。
基本粗糙模型
您可以随心所欲地浏览。这里解释了当您想要通过嵌套的has_many
关联创建快捷方式时的情况(在我发布的链接下方搜索)。
因此,给出这个解释,为了使其发挥作用,你需要做以下事情(你已经接近了):
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
另一种设置方法(可能更短)是(在这里查看这两种策略的文档):
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
希望它能有所帮助!