Rails 3 HABTM 奇怪的关联:树中的项目和员工
大家好,我必须使现有模型适应新关系。我有这个:
一个项目有很多员工。
项目的员工以某种层次结构进行组织(没什么花哨的,我解决了这个问题,为每个员工添加了一个parent_id来构建“树”)
class Employee < AR:Base
belongs_to :project
belongs_to :parent, :class_name => 'Employee'
has_many :children, :class_name => 'Employee', :foreign_column => 'parent_id'
end
class Project < AR:Base
has_many :employees,
end
这就像一个魅力,现在新的要求是:员工可以属于许多项目同时进行,并且层次结构会根据项目的不同而不同。
因此,我认为我需要一个新表来构建 HABTM,并需要一个新类来访问parent_id 来构建树。类似于
class ProjectEmployee < AR:Base
belongs_to :project
belongs_to :employee
belongs_to :parent, :class_name => 'Employee' # <--- ??????
end
class Project < AR:Base
has_many :project_employee
has_many :employees, :through => :project_employee
end
class Employee < AR:Base
has_many :project_employee
has_many :projects, :through => :project_employee
end
如何访问给定项目的员工的父级和子级?我需要根据项目员工的意愿添加和删除孩子。
谢谢你!
Hi guys I have to adapt an existing model to a new relation. I have this:
A Project has many Employees.
the Employees of a Project are organized in some kind of hierarchy (nothing fancy, I resolved this adding a parent_id for each employee to build the 'tree')
class Employee < AR:Base
belongs_to :project
belongs_to :parent, :class_name => 'Employee'
has_many :children, :class_name => 'Employee', :foreign_column => 'parent_id'
end
class Project < AR:Base
has_many :employees,
end
That worked like a charm, now the new requirement is: The Employees can belong to many Projects at the same time, and the hierarchy will be different according to the project.
So I though I will need a new table to build the HABTM, and a new class to access the parent_id to build the tree. Something like
class ProjectEmployee < AR:Base
belongs_to :project
belongs_to :employee
belongs_to :parent, :class_name => 'Employee' # <--- ??????
end
class Project < AR:Base
has_many :project_employee
has_many :employees, :through => :project_employee
end
class Employee < AR:Base
has_many :project_employee
has_many :projects, :through => :project_employee
end
How can I access the parent and the children of an employee for a given project? I need to add and remove children as wish from the employees of a project.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
必须重命名事物以更好地区分,感觉仍然有点笨拙..
鉴于一些现有记录:
添加人员:
删除人员:
--edit
Rails 关联扩展 在这里可能有一些用处。
Had to rename things for better distinction, feels a bit clumsy still..
Given some existing records:
Adding person:
Removing person:
--edit
Rails association extensions could have some use here.