0

查看 guides.rubyonrails.com,我看到了自联接的语法:

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

我想做的是更像这样的事情:

class Project < ActiveRecord::Base
  has_many :workers, :class_name => "Employee",
    :foreign_key => "manager_id"
  belongs_to :manager, :class_name => "Employee"
end

或者也许我可以多态地定义关系:

class Project < ActiveRecord::Base
  belongs_to :manager, :polymorphic => true
  has_many :employees
end

class Employee < ActiveRecord::Base
  has_many :projects, :as => :manager
end

所以我想我正在寻找的关系有点像HABTM,但在拥有和归属之间有一个具体的区别。有任何想法吗?

4

1 回答 1

2

用外行的话来说——一个经理会有很多项目,每个项目会有很多工人。对?如果是这样的话:

class Project < ActiveRecord::Base
  belongs_to :manager, :class_name => 'Employee', :foreign_key => 'manager_id'
  has_many :employees
end

class Employee < ActiveRecord::Base
  belongs_to :project
  has_many :managed_projects, :class_name => 'Project', foreign_key => 'manager_id'
  scope :managers, includes(:managed_projects).where('manager_id IS NOT NULL).order('NAME ASC')

end

这将允许员工同时成为项目中的经理和工人(例如多层项目)。

#The projects of the first manager (managers sorted by name) 
Employee.managers.first.project

# The workers (Employees) working on the project with id 1
Project.find(1).workers

# The manager (Employee) of the project with id 1
Project.find(1).manager

#Employees that are both Workers and Managers (left as an exercise)
Employee.workers_and_managers

尝试关系的另一种方法是使用 STI(单表继承),其中字段名称“类型”将确定 Employee 是 Worker 还是 Manager(互斥)

class Employee < ActiveRecord::Base
  #table Employees includes 'type' field
end

class Worker < Employee
  belongs_to :project
end

class Manager < Employee
  has_many :projects
end

现在 - 你可以这样做:

Manager.create(:name => 'John Doe') 
#you don't have to specify type - Rails will take care of it

#Find Projects managed by Employee with id 1
Manager.find(1).projects

#Find the project the Employee with id 2 is working on
Worker.find(2).project

#Find the manager of Project with id 1
Project.find(1).manager

#Find workers of Project with id 1
Project.find(1).worker
于 2012-11-04T05:30:03.067 回答