ActiveRecord查询,按关联顺序,has_many的最后一个

我试图通过最近创建的关联的recored(通信)的created_at列列出所有用户

到目前为止我所拥有的:

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

事实上, desc工作正如我所料。 问题是当订单被撤销时我尝试订购asc 。 它似乎是因为用户可以有很多通信 ,查询按照创建的第一个通信而不是最新通信的顺序返回用户列表。

如何修改查询以定位ascdesc顺序中最近创建的关联记录?

谢谢你的时间。

问题是您正在尝试按子的属性对父级进行排序,因此只有当他们的订单具有相同的方向时,您的解决方案才会起作用。

使用它的方法是使用聚合函数作为子元素的属性,如下所示:

 # 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')