Rails 5 - Action Cable - list of connected users
Asked Answered
C

3

7

I'm starting with Rails 5 and Action Cable and I would like to display a list of names of all connected registered users (something like facebook's green circle).

I managed to get the name of the user, but now I'm thinking what's the best way to store them. In node I would simply in an array on server, but as I know that is not possible in ActionCable.

What is the most effective way to do this? Storing them in database (postgres, redis)?

Chit answered 16/4, 2016 at 10:27 Comment(2)
Did you find any solution?Marten
@dedekm, can you please share your solution? Thanks.Amidase
S
2

Effectiveness completely depends on your needs. Do you need the persistence of a database?

Otherwise feel free to just use an in-memory array on your Rails server as well. Perhaps memcache, or something similar.

This is a very open-ended answer because it's a very open-ended question. I think you should give some consideration to your needs :)

Squelch answered 23/10, 2016 at 22:48 Comment(2)
how do you do this? there is some problem with Thread global variable in rails, so how can we save unpersistant data on real time server ?Tetraspore
Hi, @Matrix. I suggest that you use something like Redis to persist it if you have multiple web instances.Squelch
W
1

Add an online field to Users

class AddOnlineToUsers < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :online, :boolean, default: false
  end
end

Make an appearance channel

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

Make sure all your visitors subscribe to the AppearanceChannel when they enter your site (via some JavaScript call, see http://guides.rubyonrails.org/action_cable_overview.html#client-side-components ). Add the authorisation to Action Cable:

Like this https://rubytutorial.io/actioncable-devise-authentication/

or like that How To use devise_token_auth with ActionCable for authenticating user?

Apply again some JavaScript code to detect the incoming "{ user: current_user.id, online: :on }" message and set the green dot on a user avatar.

Wehrle answered 20/4, 2017 at 14:40 Comment(0)
M
1

I believe the best way would be to store them in redis, because it's really fast. However, more important is the fact that if you use postgres or any other RDBMS, you'll create unnecessary load on your db

Maui answered 10/11, 2017 at 10:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.