hellion
hellion

Reputation: 4830

How to pass element id to cable subscription?

I have ActionCable set up and working with a general Message channel. However, I need to limit the channel subscriptions to a single Message. How should I pass a message_id to the subscription?

I have a data attribute containing the message_id being viewed/subscribed.

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

The get_id above fails with

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

How can I limit the subscription to the specific Message?

Upvotes: 1

Views: 519

Answers (1)

hellion
hellion

Reputation: 4830

I ended up grabbing the url id using

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

and, then dropping that in as a param to the subscription

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

as far as I can tell you can't use a ready() callback in this file...no matter what I tried resulted in error.

Upvotes: 1

Related Questions