Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionCable channel not getting called on broadcasting message in rails

First of all very new to the ActionCable feature. I have been following the tutorial here: https://www.driftingruby.com/episodes/push-notifications-with-actioncable

Created a channel called web_notifications_channel and web_notifications_channel.rb:

class WebNotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_from "web_notifications_channel"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
end

web_notifications_channel.js:

import consumer from "./consumer"

consumer.subscriptions.create("WebNotificationsChannel", {
  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) {
    // Called when there's incoming data on the websocket for this channel
    console.log(`wtf`)
    
  }
});

Nothing shows in console.

Changed the adapter settings to redis in cable.yml in order to request from console:

development:
  adapter: redis

test:
  adapter: test

production:
  adapter: redis
  url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>
  channel_prefix: community_rails_production

Running console command:

ActionCable.server.broadcast 'web_notifications_channel', 'You have visited the welcome page.'

I get response as:

Broadcasting to web_notifications_channel: "You have visited the welcome page."
 => 0 

But my received method never gets called!! I am getting nuts here as cannot understand what is happening!! I have checked some similar questions but none of them helped me.

PS: I have added the gem for redis and started redis from my console.

like image 615
Fay007 Avatar asked Dec 09 '25 02:12

Fay007


1 Answers

The first param of the create method is an object, not a string

consumer.subscriptions.create({ channel: "WebNotificationsChannel" }, {
  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) {
    // Called when there's incoming data on the websocket for this channel
    console.log(`wtf`)
    
  }
});

You can also check the connection in the Network tab in your devtool, filtered by WS to see if the connection is created successfully.

The rails server, or the action cable server (if you configure action cable to run as a standalone server) has the log as well to tell you if the connection is success or failed, with the details of the error, if any.

like image 161
Tera Mind Avatar answered Dec 11 '25 16:12

Tera Mind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!