【问题标题】:Same Model for Two belongs_to Associations两个 belongs_to 关联的相同模型
【发布时间】:2011-03-14 04:34:37
【问题描述】:

我有一个模型PointOfContact,其中has_manySystems。从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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 更多详情:通过link上的关系
    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      相关资源
      最近更新 更多