【问题标题】:How do you stream a broadcast to a specific user in Rails 5 with ActionCable?如何使用 ActionCable 在 Rails 5 中向特定用户流式传输广播?
【发布时间】:2018-11-27 03:24:09
【问题描述】:

我的应用程序中有 2 种用户类型(员工和公司)。这两种用户类型都是用 Devise 创建的。我目前正在尝试使用 ActionCable 向特定公司发送通知。

我的主要问题是,当我发送通知时,每个登录的公司都会收到通知。我知道我应该以某种方式在流名称中包含公司 ID,但到目前为止我还没有运气。

我在下面包含了向所有公司发送通知的工作代码:

notifications_channel.rb

class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_from "notifications_channel"
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
end

connection.rb

module ApplicationCable
  class Connection < ActionCable::Connection::Base
  end
end

呼叫广播

ActionCable.server.broadcast 'notifications_channel', { 'My data' }

编辑

我用 javascript 记录通知的状态:

notifications.js

App.notifications = App.cable.subscriptions.create("NotificationsChannel", {
  connected: function() {
    console.log("connected");
  };

  disconnected: function() {
    console.log("disconnected");
  };

  received: function(data) {
    console.log("recieved");
  };
});

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5 actioncable


    【解决方案1】:

    像这样广播来自控制器的消息:

    # Broadcast your message
    ActionCable.server.broadcast "notifications_channel:#{target_user.id}
    

    现在用下面的代码更新app/channels/application_cable/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.name
        end
    
        protected
    
        def find_verified_user
          verified_user = User.find_by(id: cookies.signed['user.id'])
          if verified_user && cookies.signed['user.expires_at'] > Time.now
            verified_user
          else
            reject_unauthorized_connection
          end
        end
      end
    end
    

    并像这样订阅流:

    def subscribed
      stream_from "notifications_channel:#{current_user.id}"
    end
    

    注意:这只是展示如何在 Actioncable 中定位特定用户的示例。您可能需要根据以下内容修改代码 你的要求。

    我还建议观看 GoRails 的 video

    【讨论】:

    • 感谢您的意见。我用我用来跟踪通知状态的 JS 文件更新了我的问题。使用您的代码,我得到“断开连接”状态。知道为什么吗?
    • 请同时提供您的日志截图。
    • 如果您需要进一步的帮助,我们可以在这里继续讨论chat.stackoverflow.com/rooms/184302/…
    • 我必须使用“notifications_channel_#{current_user.id}”之类的语法才能使其工作,它不适用于“:”
    • @Artur79 谢谢,这是一个有趣的发现!!我会根据您的评论更新我的答案,或者随时编辑我的答案。
    【解决方案2】:

    我设法找到了解决方案。按照 Abhilashs 的回答,我走了大部分路,但我仍然无法验证公司的身份。看来 Warden 没有完全配置好,所以这篇文章使它工作:env['warden'] not working with Rails 5

    【讨论】:

      猜你喜欢
      • 2016-12-24
      • 1970-01-01
      • 2019-06-27
      • 2012-07-14
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 2017-01-04
      • 2012-05-13
      相关资源
      最近更新 更多