ActiveRecord query, order by association, last of has_many ActiveRecord query, order by association, last of has_many postgresql postgresql

ActiveRecord query, order by association, last of has_many


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:

# ascendingUser  .joins('LEFT JOIN communications ON communications.user_id = users.id')  .group('users.id')  .order('MAX(communications.created_at) ASC')# descendingUser  .joins('LEFT JOIN communications ON communications.user_id = users.id')  .group('users.id')  .order('MAX(communications.created_at) DESC')