我并没有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
锚标记,它将获得我在页面上发布的HTML类的值,然后在预订创建的params哈希中使用该值。这一切都很好,很花哨,单击该用户的用户将对该帖子进行某些操作时得到更新。但是,如果刷新页面,则该连接无法将该消费者重新连接到该帖子,因为哈希中没有参数。因此,我想知道如何摆脱这种情况。
而且,即使在rails guides页面上,它也在此处显示此内容,因此它们正在传递参数,但是在重新加载页面时如何保持连接?
因此,我从您的问题中了解到的是,当用户单击“订阅”链接时,您希望用户成为该帖子的关注者。为此,您将必须通过在User和Post作为Follower之间建立关联来将此信息存储在数据库中。然后,只要该帖子发生活动,就向该特定帖子的所有关注者的通知流广播通知。
创建一个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"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句