2014-07-10 3 views
0

사용자 테이블과 코스 테이블이 있습니다. 사용자 모델 위에는 STI를 사용하여 교사와 학생 모델이 있습니다.활성 레코드 단일 테이블 상속 결합 테이블

강사 has_many 강좌가 있지만 has_and_belongs_to_many 강좌가 있습니다.

강좌는 교사와 has_and_belongs_to_many 학생이 속합니다.

학생의 코스에 액세스하려고 시도하고 있지만 AR은 courses_users라는 조인 테이블을 찾고 광산은 courses_students라고합니다.

Student.find(100).courses 
    Student Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."type" IN ('Student') AND  "users"."id" = $1 LIMIT 1 [["id", 100]] 
PG::UndefinedTable: ERROR: relation "courses_users" does not exist 

나는 courses_users라는 새로운 조인 테이블 그냥 AR을 행복하게 만들었지 만 AR은 student_id에 테이블을 조인 찾고 있습니다하지만 난 지금 USER_ID이있는 사용자 테이블을 사용하고 있습니다.

Student.find(100).courses 
    Student Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."type" IN ('Student') AND "users"."id" = $1 LIMIT 1 [["id", 100]] 
PG::UndefinedColumn: ERROR: column courses_users.student_id does not exist 
LINE 1: ...courses"."id" = "courses_users"."course_id" WHERE "courses_u... 

STI 잘못하고 있습니까? 교사와 학생 모두 사용자로 저장 되길 원하지만 모델에는 다른 논리가 있어야합니다.

답변

1

연결과 함께 클래스 이름을 지정하려고 했습니까? 학생 : join_table => "courses_students"

OR, has_and_belongs_to_many에게 코스 클래스,

그래서, 조인 클래스 이름, 이하와 같은 jpin 테이블 이름을 지정, 학생 : 유 has_and_belongs_to_many을주는 코스 클래스

has_and_belongs_to_many : 학생 : class_name을 => "CoursesStudents"

+0

학생 모델에 join_table => "courses_students"가 추가되어 작동합니다. 감사. –

1

당신은 association_foreign_key 지정해야합니다

class Student < User 
    has_and_belongs_to_many :courses, association_foreign_key: :user_id, 
end 
+0

이것이 무엇을 의미하는지 모르겠지만 그것이 나를 위해 작동하지 않았다. 감사 :) –