这是来自this.
的后续问题这是我目前与师生建立关系的场所。
用户模型
has_many :teacher_links, :foreign_key => :student_id, :dependent => :destroy, :class_name => "TeacherStudentLink"
has_many :student_links, :foreign_key => :teacher_id, :dependent => :destroy, :class_name => "TeacherStudentLink"
has_many :students, :through => :student_links
has_many :teachers, :through => :teacher_links
TeacherStudentLink模型
class TeacherStudentLink < ActiveRecord::Base
attr_accessible :user_id, :student_id, :teacher_id
belongs_to :user
belongs_to :student, :class_name => "User"
belongs_to :teacher, :class_name => "User"
end
对我来说这似乎很尴尬因为teacher_student_links表有三列:用户,学生,老师。用户可以有很多老师,他也可以有很多学生。如果我没有教师专栏,只是假装“用户”是“老师”,那么一切都很完美。有没有办法解决这个问题?
答案 0 :(得分:1)
在评论中说什么cheeseweasel,你的链接不应该有user_id
class TeacherStudentLink < ActiveRecord::Base
attr_accessible :student_id, :teacher_id
belongs_to :student, :class_name => "User", :foreign_key => :student_id
belongs_to :teacher, :class_name => "User", :foreign_key => :teacher_id
end