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

Tob*_*sen 5 ruby-on-rails ruby-on-rails-5 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
Run Code Online (Sandbox Code Playgroud)

connection.rb

module ApplicationCable
  class Connection < ActionCable::Connection::Base
  end
end
Run Code Online (Sandbox Code Playgroud)

呼叫广播

ActionCable.server.broadcast 'notifications_channel', { 'My data' }
Run Code Online (Sandbox Code Playgroud)

编辑

我使用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");
  };
});
Run Code Online (Sandbox Code Playgroud)

Abh*_*ddy 5

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

# Broadcast your message
ActionCable.server.broadcast "notifications_channel:#{target_user.id}
Run Code Online (Sandbox Code Playgroud)

现在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
Run Code Online (Sandbox Code Playgroud)

并订阅这样的流:

def subscribed
  stream_from "notifications_channel:#{current_user.id}"
end
Run Code Online (Sandbox Code Playgroud)

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.

I also recommend watching this video by GoRails.