Rails 3 HABTM Strange Association: Project and Employee in a tree.

Posted by Mauricio on Stack Overflow See other posts from Stack Overflow or by Mauricio
Published on 2011-01-17T21:50:26Z Indexed on 2011/01/17 21:53 UTC
Read the original article Hit count: 166

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!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about design