ActionCable broadcast_to 未到达用户

ActionCable broadcast_to not reaching user

我有一个基本设置 rails + devise + actioncable。

我基本上想直接私密地向当前登录的用户发送通知。我的代码如下所示:

connection.rb

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.email
    end

    private

    def find_verified_user
      if verified_user = env['warden'].user
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end

notifications_channel.rb

class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_from current_user
  end
end

一切正常。客户端已连接,我可以在日志中看到他已正确登录。此外,我可以在 rails 控制台中看到以下输入:

[ActionCable] [admin@example.com] Registered connection (Z2lkOi8vcHJpc21vL1VzZXIvMQ)
[ActionCable] [admin@example.com] NotificationsChannel is transmitting the subscription confirmation
[ActionCable] [admin@example.com] NotificationsChannel is streaming from #<User:0x00007f87f4180b68>

但是,当尝试使用以下代码向该用户发送通知时,事件似乎没有到达用户(没有出现错误!):

2.5.1 :010 > NotificationsChannel.broadcast_to(User.first, test: 'foo')
[ActionCable] Broadcasting to notifications:Z2lkOi8vcHJpc21vL1VzZXIvMQ: {:test=>"pass"}
 => nil

而我的 javascript 消费者什么也没记录:

let cable = ActionCable.createConsumer(`ws://mydomain.com/cable`)

let actions = {
  received(payload) {
    console.log(payload) // <== this line logs nothing!
  }
}

cable.subscriptions.create('NotificationsChannel', actions)

我是不是做错了什么?

这可能是因为您使用的是 stream_from 而不是 stream_for。在您的频道中引用对象(模型)而不是字符串时,您应该使用 stream_for。尝试在 notifications_channel.rb:

中执行此操作
class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_for current_user
  end
end

这里是对文档的引用:https://api.rubyonrails.org/classes/ActionCable/Channel/Streams.html#method-i-stream_for