如何根据引用表中的最后记录时间戳对 Ruby on Rails 中的记录进行排序
我需要创建一个实时聊天应用程序,现在我有三个模型:
- ChatRoom
- ChatRoomMember
- ChatRoomMessage
在这三个模型中,我使用 includes 和 references 来获取当前的 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 列排序。我该怎么做?
这是数据库结构:
I need to create a live chat app and now I have three models :
- ChatRoom
- ChatRoomMember
- ChatRoomMessage
From this three models, I use includes and references to get the list of chat_rooms for current login user. Here is the code that I have wrote.
@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)
However, the order didn't work as I expected. What I want is that the chat_rooms are sorted by created_at column from the last message in that room. How can I do this ?
Here is the database structure :
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用关联来避免
where 'chat_room_members.user_id = ?', @current_user.id
这是我的建议,假设
User
具有如下所示的关联:Use association to avoid
where 'chat_room_members.user_id = ?', @current_user.id
Here is my suggestion, assuming
User
has associations looking like:试试这个:
Try this:
感谢大家帮助我解决这个问题。我有自己的答案。就是这样。
我使用原始查询来解决这个问题。希望这可以帮助任何有需要的人!
Thanks for everyone has help me to solve this probel. I have my own answer. Here is it.
I use raw query for solve this problem. Hope this can help anyone who need it !