Ok, I have a sample Rails app for you to fork and play with here: [https://github.com/JayMarshal/Chat]
This is how I’d probably do it.
The idea is that you treat your text messages and users not as something separate like users and recipients or something of this sort but instead you have 2 relationships between your users and messages. (will try to explain but feel free to ask clarification questions)
1) you have your User model:
class User < ActiveRecord::Base
has_many :chats, :through => :conversations
- multiple conversations(a glue/join model between users and chats)
- many chats through this conversations(these are the things that know what users talk to each other and what messages they sent)
- several text_messages - those are the messages a particular user created/sent in/to one or many chats
2) then you got the Conversation model
class Conversation < ActiveRecord::Base
This is a join model the sole purpose of which is to connect users to chats. That’s why it has only to ids: user_id and chat_id (when you add a user to a chat like this user.chats << chat ActiveRecord will automatically create one “glue” Conversation for you)
3) Chat model:
class Chat < ActiveRecord::Base
has_many :users, :through => :conversations, :uniq => true
That also as User has many conversations that connect it to users, plus it has many text_messages that were sent by users.
4) and at the end you got TextMessage itself that holds the text and knows what user created it and to what chat it belongs:
class TextMessage < ActiveRecord::Base
This setup allows you to have flexible Chats that might have one-to-one conversations(only 2 users are in and can send messages to the chat) or many-to-many conversations so that several users will receive a message sent to a Chat since they all associated to this chat.
That’s of the top of my head… there are many things that could be improved and abstracted out but this should get you going
As I mentioned above feel free to fork and play around with this sample(I left a couple of helpful creation snippets in comments the code) and feel free to ask questions.