简体   繁体   English

如何通过关联记录的属性订购Rails集合?

[英]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.

相关问题 django&sql-如何有效地存储和更新与数据库表中的记录关联的排序顺序信息? - django & sql - how can I efficiently store and update sort order information associated with records in my database table? 如何随机获取特定数量的记录,比如说 100,然后通过在 DESC 在 rails 中创建来对它们进行排序? - How can I randomly obtain a specific number of records, lets say 100, and then order them by created at DESC in rails? 如何通过Rails 4中的关联模型进行排序,并指定方向? - How to order by an associated model in Rails 4, and specify a direction? 按关联记录的条件计数顺序 - Order by conditional count of associated records Rails通过关联记录数进行选择 - Rails select by number of associated records 如何按不同表格中的两个相同属性排序? - How can I order by two same attributes from differents tables? 如何通过其中一个属性找到关联表最旧的记录过滤? - How can I find an associated table oldest record filtering by one of it's attributes? ActiveRecord:如何通过所有关联记录查找记录? - ActiveRecord: How do I find records by all of their associated records? 如何按优先级在属性中按顺序进行排序 - how to order by in rails with priority conditional in attributes 如何有效订购急切加载的记录? - How can I efficiently order eager loaded records?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM