gpt4 book ai didi

ruby-on-rails - Actioncable 计数订阅

转载 作者:可可西里 更新时间:2023-11-01 11:14:57 25 4
gpt4 key购买 nike

在我的 Ruby on Rails 项目中,我有一个 Tickets MVC。用于编辑工单(例如 ID 为 5 的工单)的典型页面是 /tickets/5/edit

在另一个页面上,我有一个简单的表格,我想实时显示有多少用户正在查看每张票(即显示有多少用户在 /tickets/1/edit , tickets/2/edit ....

每当用户登录并前往 /tickets/:id/edit 查看票证时,我都有一个 coffeescript 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/*")

这将为您提供所有活跃的 pubsub channel 。

您还可以在创建新订阅时提供 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 的所有用户计数。

关于ruby-on-rails - Actioncable 计数订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52807289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com