0

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?

Community
  • 1
  • 1
Maximus S
  • 10,759
  • 19
  • 75
  • 154

1 Answers1

1

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)
house9
  • 20,359
  • 8
  • 55
  • 61
  • 1
    Apologies if I'm being dumb (it happens more often than I'd care to admit ;)), but won't rails infer the foreign key from the association name? – Sam Peacey Jan 22 '13 at 03:15
  • 1
    it might in this case - since your association is named `student` and that will match the fk student_id; often when I need to specify class_name i have a fk that doesn't match up, so i've gotten in the habit of using fk whenever i use class_name – house9 Jan 22 '13 at 03:18