Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send ActionCable to particular user

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.

like image 221
Cameron Avatar asked May 12 '17 15:05

Cameron


2 Answers

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.

like image 160
Laith Azer Avatar answered Oct 25 '22 19:10

Laith Azer


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

like image 21
Jimmy Baker Avatar answered Oct 25 '22 20:10

Jimmy Baker