如何保持与使用从客户端传递到 ActionCable 服务器的参数的通道的连接?

How to keep a connection with a channel that uses paramaters passed from client to server for ActionCable?

我不明白 actioncable。我想让用户订阅一个 PostChannel,看起来像这样,

class PostNotificationsChannel < ApplicationCable::Channel

  def subscribed
    stream_from params[:post_id]
  end

  def unsubscribed
    stop_all_streams
  end
end

然后我有js

/javascripts/channels/post_notifications.js

$(document).on('turbolinks:load', function() {
  $("a.post_subscribe").click(function subscribeToPost() {
  var post_id = $(this).parents("li").attr("class").split(" ")[0]; // Get the post id off the page
  App.post_notifications = App.cable.subscriptions.create({channel: "PostNotificationsChannel", post_id: post_id}, {

    connected: function() {},

    disconnected: function() {},

    received: function(data) {}
    });
  });
});

所以你点击 .post_subscribe 锚标签,它会得到我在页面上的 posts HTML class 的值,然后使用它在订阅创建的参数哈希中。这一切都很好,花花公子,单击此按钮的用户将在该 post 上发生某些操作时获得更新。但是,如果您刷新页面,则该连接无法将该消费者与该 post 重新连接,因为哈希中没有参数。所以,我想知道我该如何摆脱这个。

此外,即使在 rails 指南页面上它也会显示此内容 here 所以他们正在传递参数,但是当页面重新加载时如何保持连接?

所以我从你的问题中了解到,当用户点击 "subscribe" link 时,你希望用户成为 post 的关注者。为此,您必须通过在用户和 Post 作为追随者之间建立关联,将此信息存储在数据库中。 然后,每当 activity 在 post 上发生时,向该特定 post 的所有关注者的通知流广播通知。

创建一个 NotificationsChannel,每个用户在登录该站点时都会订阅该频道,例如,id 为 1 的用户登录后,他将订阅一个通知流,该通知流对每个用户都是唯一的用户例如notify_user_1_channel

class NotificationsChannel < ApplicationCable::Channel
  def subscribed
    if params[:recepient].present?
      stream_from "notify_#{params[:recepient]}_channel"
    end
  end

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

在您的频道脚本中,

App.chat = App.cable.subscriptions.create {
            channel: "NotificationsChannel"
            recepient: $('#recepient').data("recepient")
            }

为了将收件人作为参数,在某处查看代码,最好在页脚中,

<div id="recepient" data-recepient="User_<%= current_user.id %>"></div>

并且,为了将通知广播到流中,在通知模型的 after_create_commit 中,

ActionCable.server.broadcast "notify_#{notification.recepient_type}_#{notification.recepient_id}_channel"