Topic: understanding many to many relationships

Hi,

I'm trying to create a messaging system as part of an app I'm building. I have a user model and a message model. I want to make it so that one User can send a Message to one or many other users dependent on which checkbox they click.

My models so far are like so:

*Message:*
id
from_id (User from)
to_id (User to)
title
body
date

*User*
id
name
password
other devise stuff...

What I'm struggling with is how to relate the two models to make it so that one message has one sender ID but can be sent to multiple other users.

Can someone help me out with how I might best achieve this please?

2

Re: understanding many to many relationships

One approach would be to introduce another model that defines the relationship to the users receiving the message. Something like this:

recipients (table)
id
user_id
message_id

message (model)
belongs_to :user
has_many :recipients
has_many :users, :through => :recipients

recipient (model)
belongs_to :message
belongs_to :user