ActionCable: How to use dynamic channels

人走茶凉 提交于 2020-01-01 06:45:42

问题


I have built a simple chat with Rails 5 and ActionCable where i have one simple "chat" channel.

How can i make the channel subscription and message broadcasting dynamic, so i can create chat channels and have the messages go to the right channels?

I cannot find a single code example of this unfortunately.

Update

The answer below is correct. I also found it now mentioned in the rails guide. Don't think it was there before http://edgeguides.rubyonrails.org/action_cable_overview.html#client-server-interactions-subscriptions


回答1:


Pass a roomId on your subscription creation in javascripts/channels/room.js:

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);
  });
};

In channels/room_channel.rb it becomes available as a parameter for the subscription creation, and the speak action was also just called with the correct data:

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

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

And then if you're broadcasting from a job:

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


来源:https://stackoverflow.com/questions/36926816/actioncable-how-to-use-dynamic-channels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!