dimanche 28 juin 2015

Pass custom data while subscribing and use it while publishing to a channel - private_pub

I am creating a chat module for my application and using private_pub for sending and receiving messages. I want to update the unread message counter on receiver's as soon as receiver gets the message.

Each page is subscribed to a channel where message gets published, so that every time I get the message, the counter on the page gets updated.

Following js file is executed when a new message is created.

<% publish_to conversation_messages_path(@conversation.id) do %>
    $("#messages").append("<%= escape_javascript render(:partial => 'message', :locals => { :message => @message })%>");
    $("#unread_messages_count").text("<%= current_user.received_messages.unread.size %>");
<% end %>
// @conversation.messages.where(:read => 0)
$("#newMessageForm")[0].reset();
$("#messages").scrollTop($("#messages")[0].scrollHeight);

The page gets updated but current_user.received_messages.unread.size gives me the sender's unread count, why is this so?

This means the current_user should be different for every other page who has subscribe_to that URL. As of now current_user is the one who publish_to that URL which results in the same value of unread messages count for every different client.

One possible solution is to send the user id of the one who is currently logged in while we subscribe_to a URL and in publish_to use that to get the unread messages count but the problem is I don't know how to send data while subscribing and using it in publish.

Aucun commentaire:

Enregistrer un commentaire