【问题标题】:Active Record Single Table Inheritance Join TableActive Record 单表继承连接表
【发布时间】:2014-09-01 04:38:20
【问题描述】:

我有一个用户表和一个课程表。在用户模型之上,我使用 STI 来创建教师和学生模型。

老师有_many门课程,但学生有_and_belongs_to_many门课程。

一门课程属于_一位老师,并有_and_belongs_to_许多学生。

我正在尝试访问学生的课程,但 AR 正在寻找一个名为 course_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 的 users 表。

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... 

我做错了性病吗?我希望教师和学生都保存为用户,但在模型中具有不同的逻辑。

【问题讨论】:

    标签: activerecord jointable sti


    【解决方案1】:

    您是否尝试指定类名以及关联?在 Course 类中,当你给 has_and_belongs_to_many :students 时,指定 join 类名,或 jpin 表名,如下所示,

    所以,在课程课上, has_and_belongs_to_many :students, :join_table => "courses_students"

    has_and_belongs_to_many :students, :class_name => "CoursesStudents"

    【讨论】:

    • 我在学生模型中添加了 :join_table => "courses_students" 并且它有效。谢谢。
    【解决方案2】:

    您必须指定association_foreign_key

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

    【讨论】:

    • 我不确定这意味着什么,但它对我不起作用。谢谢:)
    猜你喜欢
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    相关资源
    最近更新 更多