eabhvee
eabhvee

Reputation: 161

has_many and belongs_to association to same model using different keys

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?

Upvotes: 1

Views: 276

Answers (2)

rewritten
rewritten

Reputation: 16435

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.

Upvotes: 1

dnatoli
dnatoli

Reputation: 7012

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

Upvotes: 0

Related Questions