两个belongs_to的关联同型号 [英] Same Model for Two belongs_to Associations
问题描述
我有一个模型 PointOfContact
其中的has_many
系统
。从系统
身边,我想确定 PointOfContact
为任 technical_manager
或 project_manager
(或两者)。虽然仍只保留 PointOfContact
1时在数据库中。
我尝试如下:
类System< ActiveRecord的::基地
belongs_to的:project_manager,:CLASS_NAME => '接触点'
belongs_to的:technical_manager,:CLASS_NAME => '接触点'
结束类PointOfContact< ActiveRecord的::基地
的has_many:系统
结束
当我跑我的规格(例如下面),我可以正确地创建系统
联络点关联性。但是, PointOfContact
不知道它与系统的关联。这是为什么?
@sys = System.create
@tm = PointOfContact.create
@pm = PointOfContact.create@ sys.project_manager = @pm
@ sys.technical_manager = @tm@ pm.systems.should有(1).items#>预计1项,得到0
由于在RailsForum.com jamesw过来:<一href=\"http://railsforum.com/viewtopic.php?id=43311%22Same%20Model%20for%20Two%20belongs_to%20Associations%22\">Same两个belongs_to的关联一个解决方案模型已经找到。
类System&LT; ActiveRecord的::基地
belongs_to的:project_manager,:CLASS_NAME =&GT; PointOfContact',:foreign_key =&GT; project_manager_id
belongs_to的:technical_manager,:CLASS_NAME =&GT; PointOfContact',:foreign_key =&GT; technical_manager_id
结束类PointOfContact&LT; ActiveRecord的::基地
的has_many:project_managed_systems,:CLASS_NAME =&GT; 系统,:foreign_key =&GT; project_manager_id
的has_many:technical_managed_systems,:CLASS_NAME =&GT; 系统,:foreign_key =&GT; technical_manager_id
结束
I have an model PointOfContact
which has_many
Systems
. From the Systems
side I want to identify the PointOfContact
as either the technical_manager
or project_manager
(or both). While still only keeping the PointOfContact
1 time in the DB.
My attempt follows:
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
When I run my specs (example follows) I can correctly create the System
point of contact associations. However, the PointOfContact
is not aware of its association with System. Why is that?
@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
Thanks to jamesw over at RailsForum.com: Same Model for Two belongs_to Associations a solution has been found.
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
这篇关于两个belongs_to的关联同型号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!