开发者

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

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 emplo开发者_开发技巧yees of a project.

Thank you!


Had to rename things for better distinction, feels a bit clumsy still..

class Person < ActiveRecord::Base
  has_many :project_roles
  has_many :projects, :through => :project_roles
end

class Project < ActiveRecord::Base
  has_many :project_roles
  has_many :persons, :through => :project_roles
end

class ProjectRole < ActiveRecord::Base
  belongs_to :person
  belongs_to :project
  belongs_to :manager, :class_name => "ProjectRole"
  has_many :subordinates, :class_name => "ProjectRole", :foreign_key => "manager_id"
end

Given some existing records:

person = Person.first
project = Project.first
manager = project.project_roles.first

Adding person:

project.project_roles.create(:person => person, :manager => manager)

Removing person:

person.project_roles.find_by_project_id(project.id).destroy

--edit

Rails association extensions could have some use here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜