User Presence In a chat room (chat getting updated by simple polling)
-
22-08-2019 - |
Question
We have implemented a simple chat room feature in Rails using Simple Ajax updates. Now in every chat room a message belongs to particular user. We want to show the list of users(something like user presence). Please suggest ways. We are not using Jabber,XMPP etc.
The Chatroom model is:
class ChatRoom < ActiveRecord::Base
validates_presence_of :title
has_many :messages,:foreign_key=> "chat_room_id"
has_many :stories,:foreign_key=>"chat_room_id"
has_many :topics,:foreign_key=>"chat_room_id"
end
The messages are the chats sent of every user.
The message model is:
class Message < ActiveRecord::Base
belongs_to :user
end
The USer model is:
class User < ActiveRecord::Base
acts_as_authentic :crypto_provider => Authlogic::CryptoProviders::BCrypt
validates_presence_of :nick
validates_uniqueness_of :nick
has_many :questions
end
Please suggest ways
Solution
To keep track of which users are in which room, you could set up a HABTM relationship between the ChatRoom and User models. And, you could add a last_poll_datetime column to the User model to track the last time the user polled for messages (more on this part in a minute).
To show a list of all the users in a given room, use your HABTM join table, ChatRooms_Users. You'll be inserting/deleting from this table whenever a user joins or leaves a room.
If you want to expire users who close their browsers instead of clicking 'leave room', set up a sweeper task to run every minute that looks for users with last_poll_datetime older than one minute and remove their rows from the ChatRooms_Users join table.