gpt4 book ai didi

ruby-on-rails-3 - 两个belongs_to关联的相同模型

转载 作者:行者123 更新时间:2023-12-03 07:25:50 24 4
gpt4 key购买 nike

我有一个模型PointOfContact,其中has_many Systems。从Systems方面,我想将PointOfContact标识为technical_managerproject_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

当我运行我的规范时(示例如下),我可以正确创建系统联系点关联。然而,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

最佳答案

感谢 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

关于ruby-on-rails-3 - 两个belongs_to关联的相同模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5294775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com