ActionCable: how to use dynamic channels

I created a simple chat with Rails 5 and ActionCable, where I have one simple chat channel.

How can I make a channel subscription and message broadcast dynamic, so I can create chat channels and send messages to the desired channels?

I can not find any sample code, unfortunately.

Update

The following is the correct answer. I also found this to be mentioned in the guide. Do not think that he was there before http://edgeguides.rubyonrails.org/action_cable_overview.html#client-server-interactions-subscriptions

+3
source share
1 answer

Go through the room while creating the subscription in javascripts/channels/room.js :

 MakeMessageChannel = function(roomId) { // Create the new room channel subscription App.room = App.cable.subscriptions.create({ channel: "RoomChannel", roomId: roomId }, { connected: function() {}, disconnected: function() {}, received: function(data) { return $('#messages').append(data['message']); }, speak: function(message, roomId) { return this.perform('speak', { message: message, roomId: roomId }); } }); $(document).on('keypress', '[data-behavior~=room_speaker]', function(event) { if (event.keyCode === 13) { App.room.speak(event.target.value, roomId); event.target.value = ""; event.preventDefault(); } return $('#messages').animate({ scrollTop: $('#messages')[0].scrollHeight }, 100); }); }; 

In channels/room_channel.rb it becomes available as a parameter for creating a subscription, and the conversation action is also called with the correct data:

  def subscribed stream_from "room_channel_#{params[:roomId]}" end def speak(data) Message.create! text: data['message'], room_id: data['roomId'] end 

And then if you are broadcasting from a job:

  def perform(message) ActionCable.server.broadcast "room_channel_#{message.room_id}", message: render_message(message) end 
+9
source

Source: https://habr.com/ru/post/1247697/


All Articles