ActionCable:如何使用动态通道

ActionCable: How to use dynamic channels

我用 Rails 5 和 ActionCable 建立了一个简单的聊天室,我有一个简单的 "chat" 频道。

如何使频道订阅和消息广播动态化,以便我可以创建聊天频道并将消息发送到正确的频道?

不幸的是,我找不到一个这样的代码示例。

更新

下面的答案是正确的。我还发现现在 rails 指南中提到了它。不要认为它在 http://edgeguides.rubyonrails.org/action_cable_overview.html#client-server-interactions-subscriptions

之前就存在

javascripts/channels/room.js 中创建订阅时传递 roomId:

MakeMessageChannel = function(roomId) {
  // Create the new room channel subscription
  App.room = App.cable.subscriptions.create({
    channel: "RoomChannel",
    roomId: roomId
  }, {
    connected: function() {},
    disconnected: function() {},
    received: function(data) {
      return $('#messages').append(data['message']);
    },
    speak: function(message, roomId) {
      return this.perform('speak', {
        message: message,
        roomId: roomId
      });
    }
  });

  $(document).on('keypress', '[data-behavior~=room_speaker]', function(event) {
    if (event.keyCode === 13) {
      App.room.speak(event.target.value, roomId);
      event.target.value = "";
      event.preventDefault();
    }
    return $('#messages').animate({
      scrollTop: $('#messages')[0].scrollHeight
    }, 100);
  });
};

channels/room_channel.rb 中,它可以作为创建订阅的参数使用,并且刚刚使用正确的数据调用了说话操作:

  def subscribed
    stream_from "room_channel_#{params[:roomId]}"
  end

  def speak(data)
     Message.create! text: data['message'], room_id: data['roomId']
  end

然后,如果您是通过工作进行广播:

  def perform(message)
    ActionCable.server.broadcast "room_channel_#{message.room_id}", message: render_message(message)
  end