如何将元素ID传递给有线电视订阅?

时间:2019-05-23 22:54:10

标签: ruby-on-rails actioncable ruby-on-rails-6

我已经设置了ActionCable并使用通用的消息通道。但是,我需要将频道订阅限制为单个消息。我应该如何将message_id传递给订阅?

我有一个数据属性,其中包含正在查看/订阅的message_id。

comment_channel.js

import consumer from "./consumer"
var get_id = $('#messages').data('message-id')

consumer.subscriptions.create({
  channel: "CommentChannel", message_id: get_id

}, {

 connected() {
 console.log('connected to the comment channel')
},

disconnected() {
console.log('disconnected to the comment channel')
},

received(data) {
  console.log(data);
  $('section#comments').append(data['comment']);
}
});

CommentChannel

class CommentChannel < ApplicationCable::Channel
  def subscribed
    # stream_from "message_comments"
    # params['message_id'] should get passed in as subscription.create param
    stream_from "message:#{ params['message_id'] }:comments"
  end

  def unsubscribed
  end
end

CommentJob

class CommentRelayJob < ApplicationJob
  def perform(comment)
    ActionCable.server.broadcast("message:#{ comment.message_id }:comments", comment: CommentsController.render(partial: 'comments/comment', locals: { comment: comment }))
  end
end

上面的get_id失败

 comment_channel.js:6 Uncaught ReferenceError: $ is not defined

如何将订阅限制为特定的消息?

1 个答案:

答案 0 :(得分:0)

我最终使用来获取网址ID

var pathArray = window.location.pathname.split('/');
var secondLevelLocation = pathArray[2];

,然后将其作为订阅的参数

consumer.subscriptions.create({ 
  channel: "CommentChannel", 
  message_id: secondLevelLocation
}, ...

据我所知您无法在此文件中使用ready()回调...无论我尝试了什么都会导致错误。