Hello Rails Community! This is my first message here. I’m stuck for some days already trying to solve this issue below.
I am developing a chat application using ActionCable in Rails 7.0.4.3, but I am encountering a problem where messages aren’t being broadcast to all connected clients. I followed a tutorial for setting up the ActionCable connection, including setting up a ChatChannel and subscribing to it in the client-side JavaScript. Here’s the setup I have:
chat_channel.rb:
rubyCopy code
class ChatChannel < ApplicationCable::Channel
def subscribed
stream_from "chat"
end
def speak(data)
ActionCable.server.broadcast('chat', message: data['message'])
end
end
chat_channel.js:
javascriptCopy code
import { createConsumer } from "@rails/actioncable"
const consumer = createConsumer()
const chatChannel = consumer.subscriptions.create("ChatChannel", {
connected() {
console.log("Connected to the chat!");
},
disconnected() {
console.log("Disconnected from the chat.");
},
received(data) {
console.log("Received data: ", data);
},
speak(message) {
this.perform('speak', { message: message });
}
});
window.chatChannel = chatChannel;
I’m testing this by opening two different browsers and connecting to the chat. When I send a message from one client using chatChannel.speak('Hello, World!')
, I see the server log the broadcast message, but the other client does not receive the message. In fact, the received
function does not seem to be triggered at all.
Here’s the server log when I send a message:
ChatChannel#speak({"message"=>"Hello, World!"})
[ActionCable] Broadcasting to chat: "Hello, World!"
ChatChannel is transmitting the subscription confirmation
ChatChannel is streaming from chat_channel
I’ve checked that the ActionCable consumer is set up correctly in my JavaScript, and I don’t see any errors in the console. Can anyone provide any insight into what might be going wrong here?
Turbo is disabled on my application, but I don’t think it’s influencing here.
Any help would be greatly appreciated. Thanks in advance!