简体   繁体   English

Rails:ActiveRecord :: StatementInvalid in

[英]Rails: ActiveRecord::StatementInvalid in

I'm trying to GET all Activities (belongs_to :student) related to a Student (has_many :activities) using this in my controller: 我正在尝试在我的控制器中使用以下方法获取与学生(has_many:activities)相关的所有活动(属于:student):

@activities = Activity.joins(:student).where(student: {student_id: @student.id})

However I'm getting this as an error: 但是我得到这个错误:

SQLite3::SQLException: no such column: student.student_id: SELECT "activities".* FROM "activities" INNER JOIN "students" ON "students"."id" = "activities"."student_id" WHERE "student"."student_id" = ? SQLite3 :: SQLException:无此类列:student.student_id:选择“活动”。*从“活动”内部加入“学生”在“学生”上。“ id” =“活动”。“ student_id”在“学生”位置。” student_id“ =?

Is there a reason why you can't do this?: 您为什么不能这样做?

@activities = @student.activities

Your Student class should look like this: 您的Student班级应如下所示:

class Student < ActiveRecord::Base

  has_many :activities

end

If you want to be able to access the activities for a student directly from the Activity class I would suggest using a scope instead. 如果您希望能够直接从“ Activity类访问学生的Activity我建议改用范围。 Something like this should work: 这样的事情应该起作用:

class Activity < ActiveRecord::Base

  scope :for_student, ->(student)  { where(student_id: student) }

end

You can use the scope in a few different ways: 您可以通过几种不同的方式使用范围:

# pass in the student directly
@activities = Activity.for_student(@student) 

# pass in the student id
@activities = Activity.for_student(@student.id)

# pass in many students
@activities = Activity.for_student([@student1, @student2])

Try removing the student prefix: 尝试删除学生前缀:

@activities = Activity.joins(:student).where(student: {id: @student.id})

It's saying that it can't find a column student_id on table student . 就是说它无法在table student上找到一列student_id

@activities = Activity.where(student_id: @student.id)

要么

 @activities = @student.activities

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM