ActiveRecord查询,按关联顺序排序,has_many的最后一个 [英] ActiveRecord query, order by association, last of has_many

查看:81
本文介绍了ActiveRecord查询,按关联顺序排序,has_many的最后一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过最近创建的相关关联的摘要(通讯)的 created_at 列列出所有用户

Im trying to list all Users by the created_at column of the most recently created associated recored (communications).

到目前为止,我有什么:

What I have so far:

User.includes(:communications).order(
  'communications.created_at IS NULL, communications.created_at asc'
)

按原样, desc 可以正常工作。问题是当订单撤消时,我尝试订购 asc 。看来这是因为用户可以具有许多通信,查询将按创建的第一个通信的顺序返回用户的列表。最近。

As it is, desc works as I expect. The issue is when the order is reversed and I try order asc. It appears that is's because the user can have many communications, The query returns the list of users in order of the first communications created instead of the most recent.

如何修改查询以定位 asc 和<$ c $中最近创建的关联记录c> desc 订单?

How can I modify the query to target the most recently created associated records in both asc and desc order?

感谢您的时间。

推荐答案

问题是您尝试按孩子的属性对父级进行排序,因此您的解决方案仅在其命令具有相同方向时才有效。

Problem is you are trying to order the parent by child's attributes, so your solution will work only when their orders have the same direction.

使用它的一种方式是将聚合函数用于子级属性,如下所示:

The way to work with it is using aggregate function for the children's attribute like this:

# ascending
User
  .joins('LEFT JOIN communications ON communications.user_id = users.id')
  .group('users.id')
  .order('MAX(communications.created_at) ASC')

# descending
User
  .joins('LEFT JOIN communications ON communications.user_id = users.id')
  .group('users.id')
  .order('MAX(communications.created_at) DESC')

这篇关于ActiveRecord查询,按关联顺序排序,has_many的最后一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆