has_many and belongs_to association to same model using different keys
-
13-12-2019 - |
Question
I have two models in my rails application
Class Employee
belongs_to :cost_center
End
Class CostCenter
has_many :employees
End
Now an employee can have many cost centers as a cost center owner. How do I define this association in rails?
Solution
You have to have the correct columns, but otherwise it's easy.
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
For completeness, you should add :inverse_of
to all associations.
OTHER TIPS
I would avoid having a circular reference. If an employee belongs to a cost center, then an owner should belong to a cost center as well.
If you really needed to distinguish between owning and being employed, I would consider making two models, since an employee is a different entity to an owner.
class Owner
belongs_to :cost_center
end
class CostCenter
has_many employees
has_one owner
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow