0
我在我的Rails應用程序的has_many和belongs_to的關聯,同一型號
Class Employee
belongs_to :cost_center
End
Class CostCenter
has_many :employees
End
兩款車型現在的員工可以有很多成本中心爲成本中心所有者。我如何在rails中定義這種關聯?
我在我的Rails應用程序的has_many和belongs_to的關聯,同一型號
Class Employee
belongs_to :cost_center
End
Class CostCenter
has_many :employees
End
兩款車型現在的員工可以有很多成本中心爲成本中心所有者。我如何在rails中定義這種關聯?
您必須擁有正確的列,否則很容易。
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
添加到所有關聯中。
我會避免有一個循環引用。如果員工屬於成本中心,則所有者也應該屬於成本中心。
如果您確實需要區分擁有和被僱用,我會考慮制定兩種模式,因爲員工與所有者是不同的實體。
class Owner
belongs_to :cost_center
end
class CostCenter
has_many employees
has_one owner
end