3

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.

John
  • 6,404
  • 14
  • 54
  • 106

1 Answers1

7

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
Stéphane Bruckert
  • 21,706
  • 14
  • 92
  • 130
John
  • 6,404
  • 14
  • 54
  • 106