首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ActionCable broadcast_to未到达用户

ActionCable broadcast_to未到达用户
EN

Stack Overflow用户
提问于 2018-10-09 17:50:14
回答 1查看 2K关注 0票数 1

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

我基本上想直接和私下发送通知给目前已登录的用户。我的代码如下所示:

connection.rb

代码语言:javascript
复制
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

代码语言:javascript
复制
class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_from current_user
  end
end

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

代码语言:javascript
复制
[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>

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

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

我的javascript使用者没有记录任何东西:

代码语言: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)

我在这里做错什么了吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-09 18:02:40

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

代码语言:javascript
复制
class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_for current_user
  end
end

以下是对文档的引用:for

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52726725

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档