Ruby on Rails: Model Association with multiple foreign keys

后端 未结 1 1903
再見小時候
再見小時候 2020-12-17 06:54

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 t

相关标签:
1条回答
  • 2020-12-17 07:34

    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.

    0 讨论(0)
提交回复
热议问题