# Referencing exactly two models of the same kind

**URL:** <https://www.ruby-forum.com/t/referencing-exactly-two-models-of-the-same-kind/148377>\
**Category:** Rails\
**Created:** [September 12, 2008, 10:39am UTC](https://www.ruby-forum.com/t/referencing-exactly-two-models-of-the-same-kind/148377 "2008-09-12T10:39:54Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [September 12, 2008, 10:39am UTC](https://www.ruby-forum.com/t/referencing-exactly-two-models-of-the-same-kind/148377/1 "2008-09-12T10:39:54Z")

</div>

Hi,

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.

Fritz

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [September 12, 2008, 10:42am UTC](https://www.ruby-forum.com/t/referencing-exactly-two-models-of-the-same-kind/148377/2 "2008-09-12T10:42:15Z")

</div>

On 12 Sep 2008, at 09:39, removed\_email\_address@domain.invalid wrote:

> 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](https://www.spacevatican.org/2008/5/6/creating-multiple-associations-with-the-same-table/)**
>
> Rails makes setting up your associations dead easy and very concise. There’s a whole bunch of options that can be set however as long as you …

Fred
