ActiveRecord query, order by association, last of has_many

天大地大妈咪最大 提交于 2019-12-07 13:55:11

问题


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

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.

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

Thanks for you time.


回答1:


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


来源:https://stackoverflow.com/questions/34603949/activerecord-query-order-by-association-last-of-has-many

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!