如何使用 ActionCable 向 Rails 5 中的特定用户流式传输广播?

How do you stream a broadcast to a specific user in Rails 5 with ActionCable?

我的应用程序中有 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");
  };
});

像这样从您的控制器广播消息:

# 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

Note: This is just an example to show how to target a specific user in Actioncable. You may have to modify the code based on your requirement.

我还推荐观看 GoRails 的 video

我设法找到了解决方案。按照 Abhilash 的回答,我完成了大部分工作,但我仍然无法验证公司的身份。似乎 Warden 没有完全配置,所以这个 post 让它工作: