我正在学习Rails 5和Action Cable,想要展示所有已连接注册用户的名称列表(类似Facebook的绿色圆圈)。我已经成功获取了用户的名称,但现在正在考虑最佳存储方式。在Node中,我会简单地在服务器上使用一个数组,但我知道在ActionCable中这是不可能的。那么,最有效的方法是什么?将它们存储在数据库中(Postgres、Redis)?
效果完全取决于您的需求。您是否需要数据库的持久性?
如果不需要,请随时在Rails服务器上使用内存数组。也许是memcache或类似的东西。
这是一个非常开放式的回答,因为它是一个非常开放式的问题。我认为您应该考虑一下自己的需求 :)
Users
中添加一个online
字段。class AddOnlineToUsers < ActiveRecord::Migration[5.0]
def change
add_column :users, :online, :boolean, default: false
end
end
class AppearanceChannel < ApplicationCable::Channel
def subscribed
stream_from "appearance_channel"
if current_user
ActionCable.server.broadcast "appearance_channel", { user: current_user.id, online: :on }
current_user.online = true
current_user.save!
end
end
def unsubscribed
if current_user
# Any cleanup needed when channel is unsubscribed
ActionCable.server.broadcast "appearance_channel", { user: current_user.id, online: :off }
current_user.online = false
current_user.save!
end
end
end
确保所有访问您的网站的访客在进入时订阅AppearanceChannel
(通过一些JavaScript调用,参见http://guides.rubyonrails.org/action_cable_overview.html#client-side-components)。将授权添加到Action Cable:
像这样 https://rubytutorial.io/actioncable-devise-authentication/
或者像这样 How To use devise_token_auth with ActionCable for authenticating user?
再次应用一些JavaScript代码来检测传入的“{user:current_user.id,online::on}”消息并在用户头像上设置绿点。