I have the following code which sends an ActionCable broadcast in my Rails application:
ActionCable.server.broadcast 'notification_channel', notification: 'Test message'
The connection looks as follows:
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
def session
cookies.encrypted[Rails.application.config.session_options[:key]]
end
protected
def find_verified_user
User.find_by(id: session['user_id'])
end
end
end
However all users logged into the app will receive it. The identified_by
only makes sure that logged in users can connect to the channel but it doesn't restrict which users get the broadcast.
Is there a way to only sending a broadcast to a certain user?
The only way I could think of doing it was:
ActionCable.server.broadcast 'notification_channel', notification: 'Test message' if current_user = User.find_by(id: 1)
Where the 1
is the ID of the user I want to target.
For user-specific notifications I find it useful to have a UserChannel where the subscription is based on the current user:
class UserChannel < ApplicationCable::Channel
def subscribed
stream_for current_user
end
end
This way ActionCable creates a separate channel for each user, and you can use commands like this based on the user object:
user = User.find(params[:id])
UserChannel.broadcast_to(user, { notification: 'Test message' })
That way this channel can handle all user-specific broadcasts.
You should use a channel that's specific to that user. For example:
"notifications_channel_#{current_user.id}"
This is also documented in an example from the actioncable repo here: https://github.com/rails/rails/tree/master/actioncable#channel-example-2-receiving-new-web-notifications
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With