Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
857 views
in Technique[技术] by (71.8m points)

database - Ruby on Rails: Model Association with multiple foreign keys

I am working on a User model, and each user should be able to have both students and teachers. However, since student and teacher are both a type of User, my model got a little complicated.

This is what I am trying right now.

Teacher_student_link

class TeacherStudentLink < ActiveRecord::Base
  attr_accessible :student_id, :teacher_id, :user_id

  belongs_to :user
  belongs_to :teacher, :class_name => "User"
  belongs_to :student, :class_name => "User"
end

User

class User < ActiveRecord::Base
  has_many :teacher_student_links, :foreign_key => { :student_id, :teacher_id }, :dependent => :destroy
  has_many :students, :through => :teacher_student_links
  has_many :teachers, :through => :teacher_student_links
end

If everything works as I intended, I should be able to do

@user = User.new
@user.students
@user.teachers
@user.student.teachers

I think the only problem with above is that I can't give two foreign keys at the same time to teacher_student_link, but I'm not sure. As a workaround, I don't have teacher_id in my model yet, and just doing student.user to call the teacher. Can anyone help me with this issue?

Update: With the solution below, how should I create a new link?

def become_student
  @user = user.find(params[:id])
  @student_link = @user.student_links.create(:student_id => current_user.id)
  @teacher_link = current_user.teacher_links.create(:teacher_id => @user.id)
end

If I do it like this, is the student and teacher paired up correctly? I am confused a little because in the TeacherStudentLink, there are user, student, teacher, and I'm not sure how to deal with creating links.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should separate out the teacher_student_links association into two associations:

  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

You might need to add the foreign keys to the belongs_to association on TeacherStudentLink also

Update:

Regarding your second question about creating links, the following should work:

@user = User.find(params[:id])
@user.students << current_user

The TeacherStudentLink should be created automatically, and your associations should work if everything is set up correctly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...