【发布时间】:2019-03-19 07:46:22
【问题描述】:
在我的 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.
谢谢。
【问题讨论】:
-
你的问题是......?您是否正在尝试计算订阅或用户(并不总是相同的东西,也不应该是相同的东西)?到目前为止,您尝试了哪些代码?你被困在哪里了?
标签: ruby-on-rails websocket redis channel actioncable