gpt4 book ai didi

ruby-on-rails - 将 ActionCable 发送给特定用户

转载 作者:行者123 更新时间:2023-12-04 06:18:14 24 4
gpt4 key购买 nike

我有以下代码在我的 Rails 应用程序中发送 ActionCable 广播: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仅确保已登录的用户可以连接到 channel ,但不限制哪些用户可以接收广播。

有没有办法只向某个用户发送广播?

我能想到的唯一方法是:
ActionCable.server.broadcast 'notification_channel', notification: 'Test message' if current_user = User.find_by(id: 1)

1是我要定位的用户的 ID。

最佳答案

对于特定于用户的通知,我发现拥有一个订阅基于当前用户的 UserChannel 很有用:

class UserChannel < ApplicationCable::Channel
def subscribed
stream_for current_user
end
end

这样 ActionCable 为每个用户创建一个单独的 channel ,您可以根据用户对象使用这样的命令:
user = User.find(params[:id])
UserChannel.broadcast_to(user, { notification: 'Test message' })

这样这个 channel 就可以处理所有用户特定的广播。

关于ruby-on-rails - 将 ActionCable 发送给特定用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43941025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com