Rails 3 HABTM Strange Association: Project and Employee in a tree.
- by Mauricio
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 :childs, :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 childs of an employee for a given project? I need to add and remove childs as wish from the employees of a project.
Thank you!