收到的邮件总数

时间:2018-07-13 23:25:26

标签: ruby-on-rails ruby-on-rails-5

我按照本指南使用Rails https://github.com/mickyginger/rails-conversations构建消息功能,它不是聊天室,而是一对一的消息系统。基本上,它需要您先创建一个对话表,然后再创建一个消息表。消息表属于用户模型和会话模型。

本教程介绍的所有内容都运行良好。我想添加一项功能,以查看每个用户的消息总数,并在他们登录时将其显示在用户个人资料页面上。

因此,如果3个人分别向User_A发送1条消息,则在User_A的个人资料页面上,应该说“您有3条新消息”

我不确定在用户show动作中创建内容会更好吗?或将其放在application_controller中?

它尝试了以下操作,但是发送邮件的用户以外的每个用户都会收到通知(user_id是发送邮件的用户)。

# displays the number of unread messages in a conversation for the current_user
def unread_message_cnt(current_user)
  Message.where("user_id != ? AND read = ?", current_user.id, false).count
end 

我还尝试获取对话ID并基于此查找消息。但是现在我在遍历每个对话,而没有得到总数。

def unread_message_cnt(current_user)
  @conversations = Conversation.where("sender_id = ? OR receiver_id = ?", current_user.id, current_user.id)
  @conversations.each do |convo|
    Message.where("conversation_id = ? AND read = ? AND user_id != ?", convo.id, false, current_user.id,).count
  end
end  

如果有更好的消息传递解决方案,我也愿意接受其他建议。我宁愿使用宝石。

根据要求添加模型信息。

对话模型

class Conversation < ApplicationRecord
  belongs_to :sender, class_name: "User", foreign_key: "sender_id"
  belongs_to :receiver, class_name: "User", foreign_key: "receiver_id"

  # each conversation will have one or more messages.
  has_many :messages, dependent: :destroy

  # only one conversation is created between two users, regardless of 
  # who is the receiver and who is the sender.
  # The scope option limits the uniqueness check to just receiver_id.
  validates_uniqueness_of :sender_id, scope: :receiver_id

  # finds a conversation between two users, regardless of who the sender and receiver are.
  scope :between, ->(sender_id,receiver_id) do
    where("(conversations.sender_id = ? AND conversations.receiver_id = ?) OR 
    (conversations.receiver_id = ? AND conversations.sender_id = ?)", sender_id, receiver_id, sender_id, receiver_id)
  end  

  # return the other user (ie. not the current_user) from the conversation.
  def recipient(current_user)
    self.sender_id == current_user.id ? self.receiver : self.sender
  end

  # displays the number of unread messages in a conversation
  def unread_message_count(current_user)
    self.messages.where("user_id != ? AND read = ?", current_user.id, false).count
  end  

end

消息模型

class Message < ApplicationRecord
  belongs_to :conversation
  belongs_to :user

  validates_presence_of :body, :conversation_id, :user_id

end

在我添加的用户模型中

 has_many :conversations, dependent: :destroy

1 个答案:

答案 0 :(得分:2)

当您决定进行对话时,您处在正确的轨道上。 请尝试以下操作:

conversations = Conversation.
  where("receiver = :user_id OR sender = :user_id", user_id: currenct_user.id)

Message.where(conversation: conversations).
  where.not(user: current_user).where(read: false).count

我进一步建议您将unread范围添加到邮件模型中以提高可读性,

class Message < ApplicationRecord
  ...
  scope :unread, -> { where(read: false) }
  ...
end

现在您可以写:

Message.where(conversation: conversations).
  where.not(user: current_user).unread.count