Rails 5 ActionCable 接收未调用

Rails 5 ActionCable receive not called

我有一个在订阅和接收数据方面运行良好的 ActionCable 频道。一切正常,除了当消息沿着通道发送时没有调用 receive(data) 方法。有谁知道为什么? 我的有线频道:

class MyChannel < ApplicationCable::Channel
  def connect
  end

  def subscribed
    current_user = @authorized_user
    stream_for current_user
  end

  def receive(data)
    Rails.logger.error "received: #{data.inspect}"
    puts "received: #{data.inspect}"
  end

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

当我调用 broadcast_to 方法时,我的消费者正确地收到消息,一切正常:

 MyChannel.broadcast_to User.find(4), "test"

但是我的 receive(data) 方法从未被调用(在任何地方都看不到我的日志记录)。至于 Rails documentation goes, this should just work, but when I look at the Cable channel methods,我根本看不到接收。我错过了什么?

想通了! 您可以在 Cable 消息本身中指定您希望点击的频道操作。在我的示例中,如果我希望我的数据到达“接收”方法,我的电缆消息将如下所示:

{
    "command": "message",
    "identifier": "{\"channel\":\"MyChannel\"}",
    "data": "{\"someinfo\":\"hello world this is a test\",\"action\":\"receive\"}"
}