Search code examples
ruby-on-railsactiverecordmodel-associations

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?


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.