我正在使用一个非常简单的示例来测试 ActionCable。 我想查看网站上一次有多少用户连接。 用户未在系统中注册。 用户被分配一个带有 uuid 的 session 变量。 为了使示例尽可能简单,我没有包含模型或数据库。
#app/controller/users_controller.rb
class UsersController < ApplicationController
def index
if session[:user].nil?
session[:user] = SecureRandom.uuid
end
@user = session[:user]
UserBroadcastJob.perform_later @user
end
end
View 非常简单
#app/views/users/index.html.erb
<h1>Users</h1>
<div id="users">
<%= render "user",user: @user %>
</div>
部分用户:
#app/views/users/_user.html.erb
<div class="user">
User : <%= user %>
</div>
我使用作业来调用套接字
#app/jobs/user_broadcast_job.rb
class UserBroadcastJob < ApplicationJob
queue_as :default
def perform(user)
ActionCable.server.broadcast 'user_channel', message: render_user(user)
end
def render_user(user)
ApplicationController.renderer.render(partial: 'users/user', locals: { user: user })
end
end
还有 channel
App.user = App.cable.subscriptions.create "UserChannel",
connected: ->
disconnected: ->
received: (data) ->
console.log(data)
$("#users").prepend(data.message)
这可以正常工作。在我打开的每个浏览器中,连接的 uuid 都是可见的。 由于我不使用数据库进行持久化,因此第一个打开的浏览器具有所有 uuid,其余浏览器的 n-1 uuid 可见。这并不重要。
我的问题是:
如果浏览器关闭,如何发送消息以从模板中删除 uuid?
ActionCable 不适用于 session 。
Ruby 版本:2.4.0 rails 版本:5.1.3 通过yarn安装jquery
谢谢!!!
最佳答案
这对你很有帮助
class AppearanceChannel < ApplicationCable::Channel
def subscribed
stream_from "appearance"
@current_user = User.find(params[:room])
@current_user.appear
ActionCable.server.broadcast('appearance',{data: @current_user.appear,action: 'SubscribedList'})
end
def unsubscribed
if @current_user.present?
ActionCable.server.broadcast('appearance',{data: @current_user.disappear,action: 'SubscribedList'})
end
end
end
您可以传递参数来订阅,但无法传递参数来取消订阅。因此,当您调用 subscribe 并表示要在取消订阅端销毁我时,将 current_user 存储到一个变量中。
关于ruby-on-rails - Rails ActionCable 在浏览器关闭时取消订阅用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45753415/