I use ruby 3.0.2p107
, Rails 6.1.6
and I've a Rails backend (API) and a React Typescript frontend.
Backend code
# app/channels/notification_channel.rbclass NotificationChannel < ApplicationCable::Channel def subscribed stream_from "notification_channel_#{current_user.user_id}" end def unsubscribed; endend
# app/channels/application_cable/connection.rbmodule ApplicationCable class Connection < ActionCable::Connection::Base identified_by :current_user def connect self.current_user = find_user end private # search the current user def find_user current_user = Profile::Account.find_by(user_id: request.query_parameters[:user_id]) current_user ? current_user : reject_unauthorized_connection end endend
Frontend code
const createSubscription = (consumer: ActionCable.Cable) => { consumer.subscriptions.create({ channel: `notification_channel_${user.sub}` }, { connected: () => console.log(`connected to notifications.${user.sub}`), received: (notification) => handleReceivedNotification(notification), }); }; const handleReceivedNotification = (notification: any) => { console.log(JSON.stringify(notification)); } useEffect((): void => { if (user) setComsumer(ActionCable.createConsumer(`ws://localhost:3100/cable?user_id=${user.sub}`)); }, [user]); useEffect((): void => { if (consumer) createSubscription(consumer); }, [consumer]);
When I run the app (backend and frontend) I get the connection but can't find the subscription class.
Registered connection (Z2lkOi8vYXBpL1Byb2ZpbGU6OkFjY291bnQvMQ)Subscription class not found: "notification_channel_facebook|10157537128720479"
Also if I try a broadcast from command line, it does not work out (returns 0).
$ ActionCable.server.broadcast "notification_channel_#{user.user_id}", { action: "new_notification" }D, [2022-07-07T14:44:03.820530 #19220] DEBUG -- : [ActionCable] Broadcasting to notification_channel_facebook|10157537128720479: {:action=>"new_notification"}=> 0
I checked also the Redis channels but I can't find the notification_channel
.
Redis.new.pubsub("channels")=> ["action_cable/Z2lkOi8vYXBpL1Byb2ZpbGU6OkFjY291bnQvMQ", "_action_cable_internal"]
Here my config/cable.yml
config file
default: &default adapter: redis url: redis://localhost:6379/1development:<<: *defaulttest:<<: *defaultproduction: adapter: redis url: <%= ENV['REDIS_URL'] %> channel_prefix: api_production
Here the imports of config/application.rb
require "rails"# Pick the frameworks you want:require "active_model/railtie"require "active_job/railtie"require "active_record/railtie"require "active_storage/engine"require "action_controller/railtie"require "action_mailer/railtie"require "action_view/railtie"require "action_cable/engine"# require "sprockets/railtie"require "rails/test_unit/railtie"# activate the action mailer systemrequire "active_storage/engine"require "action_mailbox/engine"
I believe I've been through all the documentation I could find about the topic, but I'm starting loose on options. Any help would be really appreciated.
Thanks