Same Model for Two belongs_to Associations

2019-01-16 07:23发布

问题:

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.

My attempt follows:

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

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

回答1:

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