Basically I am trying to add live chatrooms to my Rails website. In my app there are 2 models: Client
and Professionnel
. Clients can ask quotes to professionels. (Edit: Quote is a model too)
For each quote I want to have a live chat available between client and professionnel.
I have already done it with a classic Message channel, appending the right message to the right quote. Yet it doesn't fulfill privacy principle as every Client and every Professionnel receive all chat messages.
At server level, I can easily subscrible the user (Client or Professionnel) to a quote specific stream like :
class QuoteChannel < ApplicationCable::Channel
def subscribed
if current_user
if current_user.quotes.any?
current_user.quotes.each do |quote|
stream_from "#{quote.hashed_id.to_s}_channel"
end
end
end
end
def unsubscribed
end
end
Though I am a bit stuck for the client side. My quote.coffee.erb doesn't accept that I use current_user
(as defined in Actioncable connection file) or any Devise identifier current_client
or current_professionnel
.
So I am not sure how I can personnalize my subscriptions on the client side. I have read that it is possible to catch an element broadcast in the message but I am not sure how I can do with my current Coffee.erb file :
App.quote = App.cable.subscriptions.create "QuoteChannel",
connected: ->
# Called when the subscription is ready for use on the server
disconnected: ->
# Called when the subscription has been terminated by the server
received: (data) ->
$('#cell'+data.quoteid).append '<div>'+'<span>'+data.message+'</span>'+'</div>'
$('.sendmessageinputtext').val("")
quoteid is passed to the received function but I need to create as many streams as the user owns quotes. In this thread http://www.thegreatcodeadventure.com/rails-5-action-cable-with-multiple-chatroom-subscriptions/ the tutor iterates across all available Chatrooms, I could do the same but it is stupid as there may be thousands of live quotes at a certain time, of which only a few are owned by the current_user
which has been allowed an Actioncable connection.