在我的Ruby on Rails项目中,我有一个Tickets 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.
谢谢。
最佳答案
您可以检查以下问题的答案:
How do I find out who is connected to ActionCable?
基本上,您必须这样做。Redis.new.pubsub("channels", "action_cable/*")
这将为您提供所有 Activity 的pubsub通道。
创建新订阅时,还可以提供userId和ticketId,例如:App.cable.subscriptions.create {channel: "TicketNotificationsChannel", ticket_id: ticketId, user_id: userId}
因此,现在Redis.new.pubsub("channels", "action_cable/*")
将以以下方式为您提供所有 Activity 的订阅["action_cable/Z2lkOi8vYXBpL1VzZXIvMTUwMjIz", "action_cable/Z2lkOi8vYXBpL1VzZXIvMTUwNTc0"]
对上面提到的字符串执行Base64.decode
将以以下方式给您输出"gid://api/User/150223/Ticket/1"
。然后,您可以在此输出上构建一些逻辑,从而为您提供特定票证ID的所有用户数。