has_many 和belongs_to 在同一模型中 [英] has_many and belongs_to within same model

查看:39
本文介绍了has_many 和belongs_to 在同一模型中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型用户,它有一个角色"属性,可以用员工"或经理"填充.现在我想要一种关系,经理有_许多员工,而员工属于_经理.

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"

即使这可行,我也怀疑这是最优雅的解决方案,因为您将有 2 个额外的外键.

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

推荐答案

我通过在用户模型中创建这些关系来解决它:

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

这篇关于has_many 和belongs_to 在同一模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆