I am making a rails app where a user can post courses and also subscribe to courses.My model files are:
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
end
The coursejoin model is like a relation between a course and a user.
When I try to do @course.students, i get error:
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" = ?
I don't know SQL much so I am not able to decipher the error.
I looked at questions with similar error but none seemed related.
I have been stuck with this for two days.
How do I fix this?
Okay i got this solved and thought i should post the solution for future reference. Basically all that was needed to be done was adding
foreign_key: "learnable_id"to
has_many :coursejoins, dependent: :destroyin course model and
foreign_key: "student_id"to
has_many :coursejoins, dependent: :destroyto user model.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.