【问题标题】:Rails: Single-table inheritance with many-to-many self-join relationships between recordsRails:单表继承,记录之间具有多对多自连接关系
【发布时间】:2017-07-16 06:01:29
【问题描述】:

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

现在一个Teacher 可以有多个Students,一个Student 可以通过多个不同的Teachers 注册课程。所以这是一个适当的多对多关系。如何为单个表中的记录之间的多对多关系建模。

我认为一种选择是在AppUser 上使用连接表——类似于app_users_app_users,带有teacher_idstudent_id 列。定义它的语法是什么?

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord has-many-through single-table-inheritance


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2017-09-05
      • 2015-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 2016-11-10
      • 1970-01-01
      相关资源
      最近更新 更多