has_many and belongs_to within same model

前端 未结 1 2016
-上瘾入骨i
-上瘾入骨i 2021-01-14 16:07

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

相关标签:
1条回答
  • 2021-01-14 16:50

    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
    
    0 讨论(0)
提交回复
热议问题