问题描述
我的频道:
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