Question

I have three models: teachers, students, and assignments

class Teacher < ActiveRecord::Base
  has_many :assignments
  has_many :students, through: assignments, uniq: true
end

For any given teacher, I would like to retrieve a list of unique students - simple enough, I just call:

teacher.students

However, I would like to order that list of students based on who has submitted assignments recently. Specifically, I would like the student with the most recently updated assignment to appear first, and so on.

I am stuck on the following code, which is not working:

teacher.students.group("assignments.student_id").order("MAX(assignments.updated_at) DESC")

Any suggestions?

Was it helpful?

Solution

It appears that my original query was correct:

teacher.students.group("assignments.student_id").order("MAX(assignments.updated_at) DESC")

I had thought it wasn't working because I had written a bad RSpec test that was failing because I wasn't handling the timestamps well. Once I used Timecop to handle the timestamps properly, the test passed.

Sorry about that.

OTHER TIPS

Not really tested, but I believe

teacher.students.includes(:assignments).order('assignments.updated_at')

should work

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top