我正在制作一个rails应用程序,用户可以在其中发布课程并订阅课程。我的模型文件是:
user.rb:
class User < ActiveRecord::Base
has_many :courses, dependent: :destroy
has_many :coursejoins, dependent: :destroy
has_many :learnables, through: :coursejoins, class_name: "Course"
has_many :comments, dependent: :destroy
...
end
course.rb:
class Course < ActiveRecord::Base
belongs_to :user
belongs_to :category
has_many :coursejoins, dependent: :destroy
has_many :students, through: :coursejoins, class_name: "User"
has_many :documents, dependent: :destroy
has_many :comments, dependent: :destroy
...
end
coursejoin.rb:
class Coursejoin < ActiveRecord::Base
belongs_to :learnable, :class_name => "Course"
belongs_to :student, :class_name => "User"
end
20160219171527_create_coursejoins.rb
class CreateCoursejoins < ActiveRecord::Migration
def change
create_table :coursejoins do |t|
t.boolean :accepted
t.timestamps
end
end
end
20160219174937_add_student_id_to_coursejoins.rb
class AddStudentIdToCoursejoins < ActiveRecord::Migration
def change
add_column :coursejoins, :student_id, :integer
end
end
20160219224309_add_learnable_id_to_coursejoins.rb
class AddLearnableIdToCoursejoins < ActiveRecord::Migration
def change
add_column :coursejoins, :learnable_id, :integer
end
端
coursejoin模型就像课程和用户之间的关系 当我尝试做@ course.students时,我得到错误:
SELECT "users".* FROM "users" INNER JOIN "coursejoins" ON "users"."id" = "coursejoins"."student_id" WHERE "coursejoins"."course_id" = ? [[nil, 1]]
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: coursejoins.course_id: SELECT "users".* FROM "users" INNER JOIN "coursejoins" ON "users"."id" = "coursejoins"."student_id" WHERE "coursejoins"."course_id" = ?
我不太了解SQL,所以我无法破译错误 我查看了类似错误的问题但似乎没有相关的问题 我已经坚持了两天 我该如何解决?
答案 0 :(得分:0)
好的,我解决了这个问题,并认为我应该发布解决方案以供将来参考。基本上所有需要做的就是在课程模型中将
foreign_key: "learnable_id"添加到
"has_many :coursejoins, dependent: :destroy",将
foreign_key: "student_id"添加到
has_many :coursejoins, dependent: :destroy到用户模型。