2
votes

I'm trying to GET all Activities (belongs_to :student) related to a Student (has_many :activities) using this in my controller:

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

3
The stacktrace is probably a good indicator here, are you sure you have the schema correct? And also, why the need to join here, why not just Activity.where(student: @student)?Nick Tomlin

3 Answers

2
votes

Is there a reason why you can't do this?:

@activities = @student.activities

Your Student class should look like this:

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. 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])
1
votes

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.

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

or

 @activities = @student.activities