43

我有一个PointOfContact模型has_many Systems。从Systems侧面我想将其标识PointOfContacttechnical_managerproject_manager(或两者)。虽然仍然只在数据库中保留PointOfContact1 次。

我的尝试如下:

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
4

2 回答 2

73

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

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
于 2011-03-18T14:57:10.540 回答
2

从 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
于 2019-03-06T17:35:26.683 回答