Rails 5没有通道的Actioncable全局消息

时间:2018-01-10 18:00:51

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

如何使用javascript向所有订阅的websocket连接发送全局消息,而无需使用频道等(例如,actioncable默认全局发送到所有打开的连接的ping消息)?

1 个答案:

答案 0 :(得分:0)

据我所知,如果没有频道,你不能直接从JavaScript中完成它(首先需要通过Redis)。

我建议您将其作为正常的帖子操作,然后在Rails中发送消息。

我会做这样的事情:

JavaScript的:

$.ajax({type: "POST", url: "/notifications", data: {notification: {message: "Hello world"}}})

控制器:

class NotificationsController < ApplicationController
  def create
    ActionCable.server.broadcast(
      "notifications_channel",
      message: params[:notification][:message]
    )
  end
end

频道:

class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_from("notifications_channel", coder: ActiveSupport::JSON) do |data|
      # data => {message: "Hello world"}
      transmit data
    end
  end
end

听JavaScript:

App.cable.subscriptions.create(
  {channel: "NotificationsChannel"},
  {
    received: function(json) {
      console.log("Received notification: " + JSON.stringify(json))
    }
  }
)