From 6752e1d44afb5dd304611e78bf98e0ababbeb1f0 Mon Sep 17 00:00:00 2001 From: Goldtean Date: Wed, 27 Jul 2016 21:17:00 -0600 Subject: [PATCH] Messages appear only in proper chatrooms --- app/assets/javascripts/channels/messages.js | 12 +++++++++--- app/channels/messages_channel.rb | 2 +- app/controllers/messages_controller.rb | 2 +- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/app/assets/javascripts/channels/messages.js b/app/assets/javascripts/channels/messages.js index 653c020..de902e5 100644 --- a/app/assets/javascripts/channels/messages.js +++ b/app/assets/javascripts/channels/messages.js @@ -1,9 +1,15 @@ -App.messages = App.cable.subscriptions.create('MessagesChannel', { +$(document).ready(function() { +chatroomId = $('input#message_chatroom_id').val(); +App.messages = App.cable.subscriptions.create({channel: 'MessagesChannel', chatroom_id: chatroomId}, { received: function(data) { - $("#messages").removeClass('hidden') + $("#messages").removeClass('hidden'); return $('#messages').append(this.renderMessage(data)); }, + chatroom_id: function(data) { + return data.chatroom_id + }, renderMessage: function(data) { return "

" + data.user + ": " + data.message + "

"; } -}); \ No newline at end of file +}); +}) \ No newline at end of file diff --git a/app/channels/messages_channel.rb b/app/channels/messages_channel.rb index b6262ca..4bbda51 100644 --- a/app/channels/messages_channel.rb +++ b/app/channels/messages_channel.rb @@ -1,5 +1,5 @@ class MessagesChannel < ApplicationCable::Channel def subscribed - stream_from 'messages' + stream_from "messages_#{params['chatroom_id']}_channel" end end diff --git a/app/controllers/messages_controller.rb b/app/controllers/messages_controller.rb index 78377f2..7ab2fa4 100644 --- a/app/controllers/messages_controller.rb +++ b/app/controllers/messages_controller.rb @@ -4,7 +4,7 @@ def create message = Message.new(message_params) message.user = current_user if message.save - ActionCable.server.broadcast 'messages', + ActionCable.server.broadcast "messages_#{message.chatroom_id}_channel", message: message.content, user: message.user.username head :ok