2012-11-04 198 views
0

看着guides.rubyonrails.com之間,我看到了自己的語法加入:ActiveRecord的:許多一對多和一對一許多相同的兩款車型

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,但具有和屬於之間的具體區別。有任何想法嗎?

回答

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(單表繼承),其中一個字段名「類型」將確定如果員工或者是一個工人或管理器(互斥)

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 
+0

所以對於STI,我會定義爲項目'belongs_to的:經理:foreign_key => 「經理標識」 \ n的has_many:工人:通過=>:worker_shift' ?假設我有一個單獨的WorkerShift模型,並且在Worker子類中定義了hmt關聯。 – Xavier

+0

其實從來沒有。經理和工人不應該是相互排斥的,所以我只會使用第一種方法。謝謝! – Xavier