Rails:ActiveRecord :: StatementInvalid in

时间:2017-01-02 22:07:44

标签: ruby-on-rails ruby-on-rails-4

我正试图在我的控制器中使用此功能获取与学生相关的所有活动(belongs_to:student)(has_many:activities):

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

但是我认为这是一个错误:

  

SQLite3 :: SQLException:没有这样的列:student.student_id:SELECT   “活动”。*来自“活动”INNER JOIN“学生”ON   “学生”。“id”=“活动”。“student_id”在哪里   “学生”。“student_id”=?

3 个答案:

答案 0 :(得分:2)

你有没有理由不能这样做?:

@activities = @student.activities

您的Student课程应如下所示:

class Student < ActiveRecord::Base

  has_many :activities

end

如果您希望能够直接从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 :(得分:1)

尝试删除学生前缀:

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

它说它无法在表student_id上找到列student

答案 2 :(得分:0)

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

 @activities = @student.activities