如何通过Javascript将参数传递给我的ActionCable订阅?

时间:2018-04-03 19:22:05

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

我使用ACtionCable创建网络套接字。这是Ruby on Rails 5.1。如何将参数传递给我的频道?我希望有一个不同的渠道,基于" worker_id" PARAM。当我创建ActionCable Web套接字时,我尝试在我的Javascript中传递参数...

    App.work = App.cable.subscriptions.create(
      'WorkChannel',
      {
        worker_id: document.getElementById('worker_id').value,
        connected: function(data) {
          var data = document.getElementById('curWork').value;
          // If tehre is a job already there, start working on it
          console.log("connected to web socket! Looking at data:" + data);
          if (data != "") {
            console.log("sending data : " + data);
          }
        },
        received: function(data) {
          console.log("received data from channel:" + data);
          _onMessage( data );
        }
      });

这是我的app / channels / work_channel.rb文件,

class WorkChannel < ApplicationCable::Channel

  # Data is received as a hash when sent by the client as JSON
  def receive(data)
    worker_id = params[:worker_id]
    puts "receive worker id: #{worker_id}"
    websocket = Rails.cache.fetch("websocket_workers")[worker_id]
    puts "received data: #{data} class: #{data.class}"
    puts "open? #{websocket.open?}"
    if !websocket.open?
      puts "not open reconnecting."
      websocket.connect
      puts "open now? #{websocket.open?}"
    end
    websocket.send( data.to_json )
  end

  def subscribed
    channel_name = "work#{params[:worker_id]}"
    puts "channel name: #{channel_name}"
    stream_from channel_name
  end

end

但是

channel_name = "work#{params[:worker_id]}"

行总是在评估&#34; work&#34;虽然我已经在我的JS中验证了值的定义,但它看起来似乎没有传递参数。在允许参数通过的同时创建消费者订阅的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

create的第一个参数应包含channelworker_id,如下所示:

App.work = App.cable.subscriptions.create(
  {
    channel: 'WorkChannel',
    worker_id: document.getElementById('worker_id').value,
  },
  {
    connected: function(data) {
      var data = document.getElementById('curWork').value;
      // If tehre is a job already there, start working on it
      console.log("connected to web socket! Looking at data:" + data);
      if (data != "") {
        console.log("sending data : " + data);
      }
    },
    received: function(data) {
      console.log("received data from channel:" + data);
      _onMessage( data );
    }
  });