Question: Rails: ActiveRecord::StatementInvalid in

Question

Rails: ActiveRecord::StatementInvalid in

Answers 3
Added at 2017-01-02 23:01
Tags
Question

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

Answers to

Rails: ActiveRecord::StatementInvalid in

nr: #1 dodano: 2017-01-02 23:01

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.

nr: #2 dodano: 2017-01-02 23:01
@activities = Activity.where(student_id: @student.id)

or

 @activities = @student.activities
nr: #3 dodano: 2017-01-02 23:01

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])
Source Show
◀ Wstecz