has_many和belongs_to使用不同的键关联到同一模型

时间:2012-10-03 07:28:35

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

我的rails应用程序中有两个模型

    Class Employee 
      belongs_to :cost_center
    End

    Class CostCenter
      has_many :employees
    End

现在,员工可以拥有多个成本中心作为成本中心所有者。如何在rails中定义此关联?

2 个答案:

答案 0 :(得分:1)

您必须拥有正确的列,否则很容易。

class Employee
  has_many :owned_cost_centers, :class_name => "CostCenter", :foreign_key => :owner_id
  belongs_to :cost_center
end

class CostCenter
  belongs_to :owner, :class_name => "Employee", :foreign_key => :owner_id
  has_many :employees
end

为了完整起见,您应该将:inverse_of添加到所有关联中。

答案 1 :(得分:0)

我会避免使用循环引用。如果员工属于成本中心,则所有者也应属于成本中心。

如果您真的需要区分拥有和就业,我会考虑制作两个模型,因为员工与所有者是不同的实体。

class Owner
  belongs_to :cost_center
end

class CostCenter
  has_many employees
  has_one owner
end
相关问题