用外行的话来说——一个经理会有很多项目,每个项目会有很多工人。对?如果是这样的话:
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