Ruby on Rails 3 - Public live chat
I'd start by checking out Ilya Grigorik's em-synchony + examples and looking at the code for the Hector private chat server gem.
See and talk to your currently online users on your site in a Ruby on Rails 3 application
How can I accurately monitor who is currently on the site and instantly remove from list when they leave?
Well using HTTP you can not do this "instantly" in a browser. Almost all solutions I see use a heartbeat technique. Every X seconds, a request is sent from the browser (using Ajax), that tells if the user is online. If you haven't heard from the user in x heartbeats, you regard the user as disconnected - even Facebook uses this, it seems. I will recommend you to drop your requirement for instant, unless it's really important.
Another approach is to implement Flash or Silverlight, to make a socket connection to the server. But the demand on the server is high, and if many people is on your site, you will run into trouble with ports and so on.
Chat belongs_to two instances of User, and User has_many :chats (ruby on rails )
I would suggest these changes (with assistance from @TonyArra):
- Chats
have_many
messages - Message
belongs_to
a chat - Chats
have_and_belongs_to_many
(orbelongs_to
) users - Users
have_and_belongs_to_many
(orhave_many
) chats
This would be the conventional way to model this, and I think it would support your use cases.
I mentioned YAGNI in the comments because the OP mentioned chats only having two users. YAGNI (you aren't going to need it, so don't built it now) is a great principle. However, many chat programs support more than two users, and sometimes just one user. You could argue that building the data model with that consideration in mind is pragmatic.
Great further reading on that subject: Preemptive Pluralization is (Probably) Not Evil
Related Topics
How to Use "Gets" on a Rake Task
Rails Convert String to Number
How to Specify Post Params in a Rails Test
How Might I Pass Text Data from the Ruby Console into My Clipboard Without Saving to a File
Deleting Table from Schema - Rails
Converting an Array of Keys and an Array of Values into a Hash in Ruby
Augmenting a Model from an External Gem
What's the Variable Scope Within 'Class_Eval' String
How to Send Mail with Rails Without a Template
Ruby Regex What Does the \1 Mean for Gsub
How to Get Request's Target Controller and Action with Rails 3
Shared Variable Among Ruby Processes
How to Install Ruby Gems When Using Rvm
Add Comment to User and Post Models (Ruby on Rails)
Rails: Your User Account Isn't Allowed to Install to the System Rubygems
Rails 5.2.0 with Ruby 2.5.1 Console - 'Warning:' 'Already' Initialized Constant Fileutils::Version