1

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

    Class Employee 
      belongs_to :cost_center
    End

    Class CostCenter
      has_many :employees
    End

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

4

2 回答 2

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到所有关联。

于 2012-10-03T07:54:52.450 回答
0

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

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

class Owner
  belongs_to :cost_center
end

class CostCenter
  has_many employees
  has_one owner
end
于 2012-10-03T07:39:23.103 回答