我有两张桌子:
所以Conversation has_many:消息和消息belongs_to:conversation
我的目标是检查current_user是否有任何未读消息(在他现有的任何对话中)以显示常规警报。 到目前为止,我已经设法为每个对话显示警报,但我很难找到一种有效的方法来实现一般的对话。
我原来的方法是:
这转化为以下代码:
@conversations = current_user.conversations
@unread = []
if @conversations.exists?
@conversations.each do |conversation|
if conversation.messages.exists?
if conversation.messages.last.user_id != current_user.id && conversation.messages.last.read == false
@unread << true
end
end
end
end
@unread.include?(true)
end
我是一个非常新的编码,但它似乎是一个非常低效的方法,必须遍历所有current_users对话并创建一个数组来检查它是否有任何'true'值。
我会遍历消息本身,但实例只有发送者的user_id,所以如果我不将它与Conversation模型链接,就无法知道是否有消息发送给他。
您是否可以通过更合适的Active Record查询或更好的方法来帮助您实现这一目标。
顺便说一句,不确定是否重要但我在开发环境中使用postgresql。
由于
答案 0 :(得分:0)
您可以通过以下内容获取conversation
的{{1}}个ID:
current_user
执行查询以使邮件计数符合您所需的条件,例如:
conv_ids = current_user.conversations.pluck(:id)
如果unread_count = Message.where(convsersation_id: conv_ids, read: false).where.not(user_id: current_user.id).count
则您可以显示提醒
我假设所有消息一旦读取就会获得unread_count > 0
值,因此即使其他任何消息(对话中的最后一条消息都有read :true
),此查询也会返回true。
PS:我没有测试过这些查询,所以请检查并在必要时进行调整。如果我在这里遗漏任何内容,请在评论中询问。