如何根据参考 Table 中的最后记录时间戳对 Rails 中 Ruby 中的记录进行排序

How to Sort Record in Ruby on Rails based on Last Record Timestamp from References Table

我需要创建一个实时聊天应用程序,现在我有三个模型:

  1. 聊天室
  2. 聊天室成员
  3. 聊天室消息

从这三个模型中,我使用 includesreferences 来获取当前登录用户的 chat_rooms 列表。这是我写的代码。

@chat_rooms = ChatRoom.includes(:members).references(:members)
@chat_rooms = @chat_rooms.includes(:messages).references(:messages)
@chat_rooms = @chat_rooms.where 'chat_room_members.user_id = ?', @current_user.id
@chat_rooms = @chat_rooms.order 'chat_room_messages.created_at DESC'
@chat_rooms = @chat_rooms.limit(limit).offset(offset)

但是,订单并没有像我预期的那样工作。我想要的是 chat_rooms 按该房间最后一条消息的 created_at 列排序。我该怎么做?

这是数据库结构:

试试这个:

ChatRoom.includes(:messages).order('chat_room_messages.created_at DESC')

使用关联来避免where 'chat_room_members.user_id = ?', @current_user.id

这是我的建议,假设 User 的关联如下所示:

class User
  has_many :chat_room_members
  has_many :chat_rooms, through: :chat_room_members
end
# list only rooms with at least on message
@chat_rooms = @current_user.chat_rooms.joins(:messages).order('chat_room_messages.created_at DESC').limit(limit).offset(offset)

# list all rooms even if there is no message attached
@chat_rooms = @current_user.chat_rooms.distinct.left_joins(:messages).order('chat_room_messages.created_at DESC').limit(limit).offset(offset)

感谢大家帮我解决了这个问题。我有自己的答案。在这里。

SELECT chat_rooms.*, (SELECT chat_room_messages.created_at FROM chat_room_messages WHERE chat_room_messages.chat_room_id = chat_rooms.id ORDER BY chat_room_messages.id DESC LIMIT 1) AS last_message_at FROM chat_rooms INNER JOIN chat_room_members ON chat_room_members.chat_room_id = chat_rooms.id WHERE chat_room_members.user_id = #{@current_user.id} ORDER BY last_message_at DESC

我使用原始查询来解决这个问题。希望能帮到有需要的人!