Ruby On Rails - many to many between the same table

ε祈祈猫儿з 提交于 2020-01-10 20:10:10

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/3098441/ruby-on-rails-many-to-many-between-the-same-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!