两个belongs_to关联的相同模型

时间:2011-03-14 04:34:37

标签: ruby-on-rails-3 associations model-associations

我有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

当我运行我的规范时(示例如下),我可以正确创建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

2 个答案:

答案 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