beaconhill
beaconhill

Reputation: 451

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:

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

Upvotes: 2

Views: 1593

Answers (3)

br3nt
br3nt

Reputation: 9576

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])

Upvotes: 2

jpheos
jpheos

Reputation: 458

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

or

 @activities = @student.activities

Upvotes: 0

codyeatworld
codyeatworld

Reputation: 1283

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.

Upvotes: 1

Related Questions