3
votes

I have a model User which has a "role" attribute which can be filled with either "employee" or "manager". Now I want a relationship where a manager has_many employees and an employee belongs_to a manager.

Is it possible to do this within the same model? I can think of something like this:

has_many :employees, class_name: "User", :foreign_key => "employee_id"
belongs_to :manager, class_name: "User", :foreign_key => "manager_id"

Even if this would work, I have doubts it is the most elegant solution, because you would have 2 extra foreign keys.

1
I think that you should be able to use the same foreign_key in each case.davmac

1 Answers

7
votes

I solved it by creating these relations in the user model:

  has_many :employees, class_name: "User", foreign_key: :manager_id
  belongs_to :manager, class_name: "User", foreign_key: :manager_id

Then I can create a manager and employee:

manager  = User.create!(first_name: "Mario", last_name: "Manager", role: "manager")
employee = User.create!(first_name: "Ed", last_name: "Employee", role: "employee", manager_id: 16)

And then it is possible to use things like:

manager.employees
employee.manager