两个belongs_to 关联的相同模型 [英] Same Model for Two belongs_to Associations

查看:30
本文介绍了两个belongs_to 关联的相同模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型 PointOfContact,其中 has_many Systems.从Systems 方面,我想将PointOfContact 标识为technical_managerproject_manager(或两者).虽然仍然只在数据库中保留 PointOfContact 1 次.

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.

我的尝试如下:

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 不知道它与系统的关联.这是为什么?

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

推荐答案

感谢在 RailsForum.com 上的 jamesw:两个belongs_to 关联的相同模型 已找到解决方案.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆