Action cable: How to broadcast the chat messages only the specific chat room in Rails 5?

40 views
Skip to first unread message

Aqib Hameed

unread,
Jun 18, 2017, 5:44:47 AM6/18/17
to Ruby on Rails: Talk

I currently have a Rails 5 application acting as my back-end,we can call this the "Core." I also have another Angular 1.6.4 application acting as my front-end, which is serving up Angular client side,And integrate with backed-end application through angular-actionable we can call this the "Front". These are two completely separate applications with completely different domains.


Basically, I am trying to integrate Action Cable through the Core and have it talk to the Front. I'm using this service here for the Front:  enter link description here. As far as the Core, that's just basic Action Cable set up.


I have a list of chat rooms on admin side. 


Problem: I sent message from client side but it broadcast message to all the chat rooms in admin side.I try to give the specific path of chat room in stream but still it broadcast message to all chat rooms.

I want to broadcast the message to specific chat room.How i give specific path to broadcast message to specific chat room ????


Back-end


chat_channel.rb

class ChatChannel < ApplicationCable::Channel
   def subscribed
      stream_from stream_name
   end
   def unsubscribed
     stop_all_streams
   end

   def receive(data)
       ActionCable.server.broadcast stream_name,  data.fetch('message')
   end

   private

   def stream_name
      "chat_channel_#{chat_id}"
   end

   def chat_id
      params.fetch('data').fetch('chat')
   end
end
Front-end
chatCtrl.js

app.run(function (ActionCableConfig){
   ActionCableConfig.debug = true;
   ActionCableConfig.wsUri= "ws://localhost:3000/cable";
});
app.controller('chatCtrl', ['$scope', 'ActionCableChannel',
function($scope, ActionCableChannel) {

  var consumer = new ActionCableChannel("ChatChannel", { chat: 'localhost:3000/#!/chat/1'});
  var callback = function(message) {
    $scope.myData.push(message);
  };
  consumer.subscribe(callback).then(function(){
    $scope.sendToMyChannel = function(message){
      consumer.send(response.data);
    };
    $scope.$on("$destroy", function(){
      consumer.unsubscribe().then(function(){ $scope.sendToMyChannel = undefined; });
    });
  });
}
]);
Reply all
Reply to author
Forward
0 new messages