Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user is online in realtime

I want to check if a User is online at this moment. This should be shown on the users profile.

I got this in my application_controller

after_filter :user_activity

private

  def user_activity
    current_user.try :touch
  end

I defined this in the user-model

def online?
 updated_at > 10.minutes.ago
end

I can check in the view if the user is online: (HAML)

- if @user.online?

This works, but there is always a reload of the page required to update this information. How can it made into a realtimecheck? Maybe using ActionCable?

PS: using devise

like image 308
Max Avatar asked Oct 27 '25 07:10

Max


1 Answers

Yes, Action Cable can be used for this. The Rails guide has (half of) an example of this here: Action Cable Overview -- 6.1 Example 1: User Appearance

Basically, you create an AppearanceChannel and every user is subscribed to it. Subscribing calls the appear function for the current_user, which can then be broadcast out (e.g., to show online status to other users), typically via a background job like BroadcastAppearanceJob. (I have just started working through this myself).

like image 115
clairity Avatar answered Oct 29 '25 21:10

clairity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!