Send ActionCable to particular user

Viewed 3701

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.

2 Answers
Related