在我的Ruby on Rails项目中,我有一个票证MVC。用于编辑票证(例如,id为5的票证)的典型页面将是/tickets/5/edit。
在另一个页面上,我有一个简单的表,我想要实时显示每个票证有多少用户正在查看(即显示有多少用户在/tickets/1/edit、tickets/2/edit上...
每当用户登录并查看/tickets/:id/edit上的票据时,我都会有一个如下所示的ticket_notifications.coffee:
$ ->
if $('body').attr('data-controller') == 'tickets' && $('body').attr('data-action') == 'edit'
ticketId = document.getElementById('ticket_id').value
App.ticket_notifications = App.cable.subscriptions.create {channel: "TicketNotificationsChannel", ticket_id: ticketId},
connected: ->
# Called when the subscription is ready for use on the server
disconnected: ->
# Called when the subscription has been terminated by the server
received: (data) ->我的app/channels/ticket_notifications_channel.rb看起来像这样:
class TicketNotificationsChannel < ApplicationCable::Channel
def subscribed
# stream_from "some_channel"
if current_user&.account
stream_from "ticket_notifications_channel_#{current_user.account_id}"
if params[:ticket_id]
if Ticket.find(params[:ticket_id]).account == current_user.account
ActionCable.server.broadcast "ticket_notifications_channel_#{current_user.account_id}",
{stuff: "Agent #{current_user.email} is viewing ticket #{params[:ticket_id]}"}
end
end
end
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end前端表格如下所示(我使用的是Slim,但类似于erb):
table.table.table-hover
thead
tr
th
| Ticket #
th
| Short Code
th
| Mobile Number
th
| Number of Tickets
th
| Updated At
th
| Viewers
tbody
- unless @tickets.empty?
- current_time = Time.now
- @tickets.each do |tkt|
- tkt_updated_at = tkt.updated_at
tr.m-unread.m-tr-clickable data-href=edit_ticket_path(id: tkt.id)
td
b #{tkt.id}
td
b #{tkt.short_code}
td
b #{tkt.mobile_number}
td
- if last_message = tkt.messages&.last&.body
b #{last_message[0..60]}
td
- if (current_time-tkt_updated_at) <= time_period
b #{time_ago_in_words(tkt_updated_at)} ago
- else
b #{tkt_updated_at.in_time_zone.strftime('%b %e %H:%M:%S %Y')}
td
b Count how many subscriptions to tickets_notifications channel with params tkt.id here. 谢谢。
发布于 2018-10-15 13:19:40
您可以检查以下问题的答案:
How do I find out who is connected to ActionCable?
基本上你必须这样做。
Redis.new.pubsub("channels", "action_cable/*")
这将为您提供所有活动的pubsub通道。
此外,您还可以在创建新订阅时提供userId以及ticketId,如下所示:
App.cable.subscriptions.create {channel: "TicketNotificationsChannel", ticket_id: ticketId, user_id: userId}
因此,现在Redis.new.pubsub("channels", "action_cable/*")将以以下方式为您提供所有活动订阅
["action_cable/Z2lkOi8vYXBpL1VzZXIvMTUwMjIz", "action_cable/Z2lkOi8vYXBpL1VzZXIvMTUwNTc0"]
对上面提到的字符串执行Base64.decode将以"gid://api/User/150223/Ticket/1"的方式输出。然后,您可以在此输出上构建一些逻辑,为您提供特定票证id的所有用户的计数。
https://stackoverflow.com/questions/52807289
复制相似问题