【发布时间】:2016-09-10 07:38:19
【问题描述】:
我使用本教程为我的 Rails 应用程序创建了一个消息传递系统:Create a Simple Messaging System on Rails,作者是 Dana Mulder。它可以创造奇迹,但我在稍微调整它时遇到了问题。 是否有人对创建显示每个对话的最新消息的对话收件箱有见解?更多详细信息如下。
系统中有两种模型:Conversation和Message:
- 对话有一个 user1_id 和一个 user2_id。
- 消息具有 user_id、body 和 conversation_id。
因此,每个会话可以有多条消息,并且每条消息都属于发送它的用户。
我构建了一个 ConversationsController 来显示索引中的所有消息。 不过,我想要的是只按顺序显示每个对话的最新消息。
我将在此处粘贴当前版本的 Conversations#Index 操作,以及我设想的操作(这会产生一个错误,我将在下面描述)。
Working Conversations#Index(显示所有消息):
@conversations = Conversation.where("user1_id = #{current_user.id} OR user2_id = #{current_user.id}")
@array = []
@conversations.each do |item|
@array.push(item.id)
end
@messages = Message.where("conversation_id in (?)", @array)
Conversations#Index 无效(应仅显示每个对话的最新消息:
@conversations = Conversation.where("user1_id = #{current_user.id} OR user2_id = #{current_user.id}").order("updated_at DESC")
@array = []
@conversations.each do |item|
@array.push(item.id)
end
@list = []
@array.each do |i|
@id = Message.where("conversation_id = (?)", i).last
@list.push(@id.id)
end
@messages = Message.where("id in (?)", @list)
当我输入后一段代码时,收件箱根本没有显示任何消息。任何想法为什么?
日志
Started GET "/conversations" for 99.234.104.113 at 2016-05-14 04:19:05 +0000
Processing by ConversationsController#index as HTML
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Conversation Load (0.3ms) SELECT "conversations".* FROM "conversations" WHERE (1 IN (sender_id, recipient_id)) ORDER BY updated_at DESC
Message Load (0.4ms) SELECT "messages".* FROM "messages" WHERE (conversation_id = 2) ORDER BY "messages"."id" DESC LIMIT 1
Message Load (0.3ms) SELECT "messages".* FROM "messages" WHERE (conversation_id = 1) ORDER BY "messages"."id" DESC LIMIT 1
(0.2ms) SELECT COUNT(*) FROM "conversations" WHERE (1 IN (sender_id, recipient_id))
Conversation Load (0.3ms) SELECT "conversations".* FROM "conversations" WHERE (1 IN (sender_id, recipient_id)) ORDER BY updated_at DESC LIMIT 10 OFFSET 0
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 3]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 2]]
Rendered conversations/_convo.html.erb (150.4ms)
Message Load (0.3ms) SELECT "messages".* FROM "messages" WHERE (id in (10,9)) LIMIT 10 OFFSET 0
Rendered conversations/_message.html.erb (1.0ms)
Rendered conversations/index.html.erb within layouts/application (157.4ms)
Rendered layouts/_shim.html.erb (0.1ms)
Rendered layouts/_header.html.erb (1.6ms)
Rendered layouts/_footer.html.erb (0.5ms)
Completed 200 OK in 299ms (Views: 292.1ms | ActiveRecord: 2.3ms)
【问题讨论】:
标签: ruby-on-rails ruby search