[英]How can I order a Rails collection by the attributes of associated records?
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. 我以为它没有用,因为我写了一个糟糕的RSpec测试失败,因为我没有很好地处理时间戳。 Once I used Timecop to handle the timestamps properly, the test passed.
一旦我使用Timecop正确处理时间戳,测试就通过了。
Sorry about that. 对于那个很抱歉。
Not really tested, but I believe 没有真正测试过,但我相信
teacher.students.includes(:assignments).order('assignments.updated_at')
should work 应该管用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.