我有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
答案 0 :(得分:65)
感谢jamesw在RailsForum.com: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
答案 1 :(得分:0)
从Rails文档中:
带注释的示例:
# Employee class with two Employee associations
class Employee < ApplicationRecord
# Employees I manage
has_many :subordinates, class_name: "Employee",
foreign_key: "manager_id"
# Employee that manages me
# NOTE: with :manager reference name, foreign_key defaults to "manager_id",
# hence it is not needed as above. Favor "convention over configuration".
belongs_to :manager, class_name: "Employee"
end