Rails:单表继承,记录之间具有多对多自连接关系

时间:2021-02-17 15:52:11

I am modeling a learning web app with two distinct roles, Teachers and Students. There is a lot of common behaviour between both and it makes sense to abstract them to an AppUser base class. It also helps to use single-table inheritance for the two models, with a single table app_users storing both types.

我正在建模一个学习网络应用程序,它有两个不同的角色,教师和学生。两者之间有很多共同的行为,将它们抽象到AppUser基类是有意义的。它还有助于为两个模型使用单表继承,使用单个表app_users存储这两种类型。

Now a Teacher can have many Students, and a Student could be enrolled in courses by many different Teachers. So it's a proper many-to-many relationship. How may I model a many-to-many relationship between records in a single table.

现在,教师可以有很多学生,学生可以参加许多不同教师的课程。所以这是一个适当的多对多关系。我如何在单个表中建立记录之间的多对多关系。

I think one option is to use a join table on AppUser - something like app_users_app_users, with a teacher_id and a student_id column. What's the syntax to define this?

我认为一个选项是在AppUser上使用连接表 - 类似于app_users_app_users,具有teacher_id和student_id列。定义它的语法是什么?

An alternative is to use a model, like AppUserRelationship, and then define has_many through relations. What's the way to do this?

另一种方法是使用模型,如AppUserRelationship,然后通过关系定义has_many。这样做的方法是什么?

1 个解决方案

#1


1  

this just an idea, create new relation table to hold many to many relation between

这只是一个想法,创建新的关系表来保持多对多关系

class Relation < ActiveRecord::Base
  belongs_to :student, foreign_key: "student_id", class_name: "User"
  belongs_to :teacher, foreign_key: "teacher_id", class_name: "User"
end

class User < ActiveRecord::Base
  # as teacher
    has_many: student_relations, foreign_key: :teacher_id, class_name: "Relation"
    has_many: students, through: :student_relations, source: :student
  # as student
    has_many: teacher_relations, foreign_key: :student_id, class_name: "Relation"
    has_many: teachers, through: :teacher_relations, source: :teacher
end

#1


1  

this just an idea, create new relation table to hold many to many relation between

这只是一个想法,创建新的关系表来保持多对多关系

class Relation < ActiveRecord::Base
  belongs_to :student, foreign_key: "student_id", class_name: "User"
  belongs_to :teacher, foreign_key: "teacher_id", class_name: "User"
end

class User < ActiveRecord::Base
  # as teacher
    has_many: student_relations, foreign_key: :teacher_id, class_name: "Relation"
    has_many: students, through: :student_relations, source: :student
  # as student
    has_many: teacher_relations, foreign_key: :student_id, class_name: "Relation"
    has_many: teachers, through: :teacher_relations, source: :teacher
end