Many to many AND one to many association

I want create mini mail service in my website, but i have little problem mapping assotiation. I have two models User and Message, every message have one sender and many recievers. I map sender with user_id field in message and recievers with table messagesusers with user_id and message_id fields. In model message I add belongs_to :user has_many :users and in messagesuser belongs_to :user belongs_to :message I don't know what add in user model, i try with has_many :messages but doesn't work. Thanks and sorry for my poor english

SaThot wrote in post #957715:

I have two models User and Message, every message have one sender and many recievers.

First thing to understand is that there is no many-to-many association here. As you said a Message belongs_to a user and Message has many recipients, which are Users. So you basically just need to add a foreign key to User to keep track of the one-to-many relation Message <--->> User. We just need to do a bit of convention overriding to accomplish this:

User   has_many :messages

Message   belongs_to :user   has_many :recipients, :class_name => "User", :foreign_key => :recipient_message_id

Or if you want to make things more clear you could do:

Message   belongs_to :sender, :class_name => "User", :foreign_key => :sender_id   has_many :recipients, :class_name => "User", :foreign_key => :recipient_message_id