我正在研究用户模型,每个用户都应该能够同时拥有学生和教师.但是,由于学生和老师都是用户类型,我的模型有点复杂.
这就是我现在正在尝试的.
Teacher_student_link
@H_502_6@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 @H_502_6@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如果一切按照我的意图行事,我应该能做到
@H_502_6@@user = User.new @user.students @user.teachers @user.student.teachers我认为上面唯一的问题是我不能同时给teacher_student_link两个外键,但我不确定.作为一种解决方法,我的模型中还没有teacher_id,只是让student.user给老师打电话.任何人都可以帮我解决这个问题吗?
@H_502_6@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如果我这样做,学生和老师是否配对正确?
我很困惑,因为在TeacherStudentLink中,有用户,学生,老师,我不知道如何处理创建链接.
解决方法
您应该将teacher_student_links关联分为两个关联:
@H_502_6@has_many :teacher_links,:foreign_key => :student_id,:dependent => :destroy,:class_name => "TeacherStudentLink"
has_many :student_links,:foreign_key => :teacher_id,:class_name => "TeacherStudentLink"
has_many :students,:through => :student_links
has_many :teachers,:through => :teacher_links
您可能还需要将外键添加到TeacherStudentLink上的belongs_to关联
更新:
@H_502_6@@user = User.find(params[:id]) @user.students << current_user应自动创建TeacherStudentLink,如果一切设置正确,您的关联应该有效.