2011-03-14 66 views
36

我有一個型號PointOfContact其中has_manySystems。從Systems方面我想確定PointOfContact作爲technical_managerproject_manager(或兩者)。雖然仍然只在數據庫中保留PointOfContact 1次。相同型號的兩個belongs_to協會

我嘗試如下:

class System < ActiveRecord::Base 
    belongs_to :project_manager, :class_name => 'PointOfContact' 
    belongs_to :technical_manager, :class_name => 'PointOfContact' 
end 

class PointOfContact < ActiveRecord::Base 
    has_many :systems 
end 

當我跑我的規格(例如如下)我可以正確地創建System點接觸關聯。但是,PointOfContact不知道它與系統的關聯。這是爲什麼?

@sys = System.create 
@tm = PointOfContact.create 
@pm = PointOfContact.create 

@sys.project_manager = @pm 
@sys.technical_manager = @tm 

@pm.systems.should have(1).items #> expected 1 items, got 0 

回答

62

由於在RailsForum.com jamesw過來:Same Model for Two belongs_to Associations的解決方案已被發現。

class System < ActiveRecord::Base 
    belongs_to :project_manager, :class_name => 'PointOfContact', :foreign_key => 'project_manager_id' 
    belongs_to :technical_manager, :class_name => 'PointOfContact', :foreign_key => 'technical_manager_id' 
end 

class PointOfContact < ActiveRecord::Base 
    has_many :project_managed_systems, :class_name => 'System', :foreign_key => 'project_manager_id' 
    has_many :technical_managed_systems, :class_name => 'System', :foreign_key => 'technical_manager_id' 
end 
+0

更多詳情:通過關於[link](http://railscasts.com/episodes/163-self-referential-association?view=asciicast) – Zippie 2013-03-06 17:18:09