[英]Rails: ActiveRecord::StatementInvalid in
我正在嘗試在我的控制器中使用以下方法獲取與學生(has_many:activities)相關的所有活動(屬於:student):
@activities = Activity.joins(:student).where(student: {student_id: @student.id})
但是我得到這個錯誤:
SQLite3 :: SQLException:無此類列:student.student_id:選擇“活動”。*從“活動”內部加入“學生”在“學生”上。“ id” =“活動”。“ student_id”在“學生”位置。” student_id“ =?
您為什么不能這樣做?
@activities = @student.activities
您的Student
班級應如下所示:
class Student < ActiveRecord::Base
has_many :activities
end
如果您希望能夠直接從“ Activity
類訪問學生的Activity
我建議改用范圍。 這樣的事情應該起作用:
class Activity < ActiveRecord::Base
scope :for_student, ->(student) { where(student_id: student) }
end
您可以通過幾種不同的方式使用范圍:
# 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])
嘗試刪除學生前綴:
@activities = Activity.joins(:student).where(student: {id: @student.id})
就是說它無法在table student
上找到一列student_id
。
@activities = Activity.where(student_id: @student.id)
要么
@activities = @student.activities
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.