将 ActionCable 发送给特定用户 [英] Send ActionCable to particular user

查看:55
本文介绍了将 ActionCable 发送给特定用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码在我的 Rails 应用程序中发送 ActionCable 广播:ActionCable.server.broadcast 'notification_channel',通知:'测试消息'

I have the following code which sends an ActionCable broadcast in my Rails application: ActionCable.server.broadcast 'notification_channel', notification: 'Test message'

连接如下:

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

但是,所有登录该应用的用户都会收到它.identified_by 仅确保已登录的用户可以连接到频道,但不限制哪些用户可以接收广播.

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)

其中 1 是我要定位的用户的 ID.

Where the 1 is the ID of the user I want to target.

推荐答案

您应该使用特定于该用户的频道.例如:

You should use a channel that's specific to that user. For example:

"notifications_channel_#{current_user.id}"

这里的 actioncable 存储库示例中也记录了这一点:https://github.com/rails/rails/tree/master/actioncable#channel-example-2-receiving-new-web-notifications

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

这篇关于将 ActionCable 发送给特定用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆