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?

有帮助吗?

解决方案

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.

其他提示

Not really tested, but I believe

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

should work

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top