看看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,但具有和属于的具体区别。有什么想法吗?
答案 0 :(得分: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(单表继承),其中字段名称'type'将确定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