Referencing exactly two models of the same kind


how do I solve this in Rails: Lets say I have a User and a Message. Now, a Message is sent from one User to another User, which means that in the Message I have to reference a User twice!

This seems to be a problem, if I do not user one-to-many or many-to- many relationships, because it seems to me as if I could reference a Model of the same type only once.

However, I would like the Message model to contain 2 User fields. So this would look something like this:

class User ActiveRecord::Base # Given a User, I do not require to be able to retrieve all his messages. end

class Message < ActiveRecord::Base belongs_to :user; # Sender belongs_to :user2; # Receiver end

The DB Tables should look something like this:

users id

messages id, user_id, user2_id;

How do the Rails models and the database tables look like? I'm generally wondering how to reference more than one model of the same kind from within another model, without using many_to_many or one_to_many relationships.


I once wrote a blog post that explains this: Creating multiple associations with the same table - Space Vatican