0

I have a users table and a course table. On top of the user model, I'm using STI to have a teacher and a student model.

A teacher has_many courses, but a student has_and_belongs_to_many courses.

A course belongs_to a teacher and has_and_belongs_to_many students.

I'm trying to access a student's courses but AR is looking for a join table called courses_users while mine is called 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

I created a new join table called courses_users just to make AR happy but AR is looking to join the tables on student_id but I'm now using the users table that has a 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... 

Am I doing STI wrong? I want Teachers and Students to both be saved as users but have different logic in the model.

2 Answers2

1

Did you try specifying the class name along with the association?. In Course class when u give has_and_belongs_to_many :students, specify the join class name, or jpin table name like below,

So, in Course class, has_and_belongs_to_many :students, :join_table => "courses_students"

OR

has_and_belongs_to_many :students, :class_name => "CoursesStudents"

Bhavya
  • 572
  • 3
  • 14
1

You must specify the association_foreign_key:

class Student < User
  has_and_belongs_to_many :courses, association_foreign_key: :user_id, 
end
infused
  • 24,000
  • 13
  • 68
  • 78