Reputation: 4830
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.
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']);
}
});
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
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
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