Ruby on Rails的 - 很多很多的同桌之间 [英] Ruby On Rails - many to many between the same table
问题描述
我想创建Rails中一个比较复杂的关系,和我有一些很难找到这样做的最佳方式。我在每个用户作为一个老师和一个学生一个用户表。我想有一个的has_many学生(这也只是用户)和的has_many教师(这也只是用户)。我不想做任何的子类或单表继承。我只是希望两个不同的MANY_TO_MANY的用户之间。什么是做到这一点的最好方法是什么?这是一个坏主意呢?有没有更好的解决办法?
I am trying to create a somewhat complex relationship in Rails, and am having some trouble finding the best way to do so. I have a Users table in which each user acts as a teacher and a student. I would like to have a has_many "students" (which are also just Users) and a has_many "teachers" (which are also just Users). I do not want to do any subclassing or single table inheritance. I just want two different many_to_many's between Users. What is the best way to do this? Is this a bad idea to do? Is there a better solution?
推荐答案
您应该能够建立一个分配模型,并使用它,就像任何其他的许多一对多的关系:
you should be able to setup an assignment model and use it as you would any other many-to-many relationship:
class User < ActiveRecord::Base
has_many :student_teacher_assignments, :class_name => "StudentTeacherAssignment", :foreign_key => "student_id"
has_many :teachers, :through => :student_teacher_assignments
has_many :teacher_student_assignments, :class_name => "StudentTeacherAssignment", :foreign_key => "teacher_id"
has_many :students, :through => :teacher_student_assignments
end
class StudentTeacherAssignment < ActiveRecord::Base
belongs_to :student, :class_name => "User"
belongs_to :teacher, :class_name => "User"
end
我会改变分配的名称要少一些类似的,更有意义的,但这个概念应该保持不变
I would change the names of the assignments to be a little less similar and more meaningful, but the concept should remain the same
这篇关于Ruby on Rails的 - 很多很多的同桌之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!