Search code examples
ruby-on-railsmodel-associationsrails-activerecord

Self-referential association


It's a follow-up question from this.

This is my current setting to make a teacher-student relationship.

User Model

  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 Model

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

It seems awkward to me because the teacher_student_links table has three columns: user, student, teacher. User can have many teachers, and he can also have many students. If I don't have the teacher column, and just pretend "user" is a "teacher", everything works out perfectly. Is there a way to fix this issue?


Solution

  • what cheeseweasel said in the comments, your link should not have a 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
    
    • belongs_to foreign_key specifies the foreign key on the current table (link)
    • has_many foreign_key specifies the foreign key on the other table (link)