2017-01-02 76 views
2

我試圖讓所有的活動(belongs_to的:學生)相關的學生Rails的:ActiveRecord的:: StatementInvalid在

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

但是我越來越:在我的控制器使用這個(的has_many活動)這是一個錯誤:

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" = ?

+0

堆棧跟蹤可能是一個很好的指標在這裏,你確定你有正確的模式?此外,爲什麼需要在這裏「加入」,爲什麼不只是'Activity.where(student:@student)'? –

回答

2

是否有一個理由,爲什麼你不能做到這一點?:

@activities = @student.activities 

Student類應該是這樣的:

class Student < ActiveRecord::Base 

    has_many :activities 

end 

如果你想能夠訪問t他直接從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]) 
1

嘗試刪除學生的前綴:

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

它說,它CA沒有在表student上找到列student_id

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

@activities = @student.activities 
相關問題