两个belongs_to关联的相同模型
我有一个模型 PointOfContact
,其中 has_many
Systems
。从Systems
方面,我想将PointOfContact
标识为technical_manager
或project_manager
(或两者)。同时仍然只在数据库中保留 PointOfContact
1 次。
我的尝试如下:
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
不知道它与 System 的关联。这是为什么?
@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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
感谢 RailsForum.com 上的 jamesw: 两个属于关联的相同模型已找到解决方案。
Thanks to jamesw over at RailsForum.com: Same Model for Two belongs_to Associations a solution has been found.
来自 Rails 文档:
带注释的示例:
From the Rails documentation:
Annotated example: