如何在频道流式传输后调用控制器操作?

问题描述

我的频道:

class DevicesChannel < ApplicationCable::Channel
  def subscribed
    stream_from 'datas_channel',coder: ActiveSupport::JSON
  end

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

  def receive
    data = Deviceinformation.create(message: "oks")
    ActionCable.server.broadcast("datas_channel",data)
  end
end

发送订阅请求,做了:

{
  "command": "subscribe","identifier": "{\"channel\":\"DevicesChannel\"}"
}

并且,写消息:

{
    "command": "message","identifier": "{\"channel\":\"DevicesChannel\"}","data": "{\"message\":\"Hello world\",\"action\": \"receive\"}"
}

根据上述要求,它运行良好。它调用接收方法并且运行良好。

但我想调用控制器动作“创建”,即

class DeviceinformationsController < ApplicationController
  def create
    data = Deviceinformation.create(message: 'Hello world')
    ActionCable.server.broadcast("datas_channel",data)
  end
end

可以吗?任何帮助将非常感激。我是网络套接字 API 的新手

解决方法

可以按照 Rails-core 的方式进行集成测试: https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/testing/integration.rb (阅读代码 ActionDispatch::Integration::Session#process)

我做了一个演示(获取所有目标 - TargetsController#index)

class DevChannel < ApplicationCable::Channel
  # ...
  def receive(data)
    session = ActionDispatch::Integration::Session.new(Rails.application)
    path = ENV.fetch("APPLICATION_HOST") + Rails.application.routes.url_helpers.targets_path
    session.get(path)
    ActionCable.server.broadcast("DevChannel",session.response.body)
  end
end

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...