# Problem with two foreign keys

**URL:** <https://www.ruby-forum.com/t/problem-with-two-foreign-keys/142344>\
**Category:** Rails\
**Created:** [July 7, 2008, 3:59am UTC](https://www.ruby-forum.com/t/problem-with-two-foreign-keys/142344 "2008-07-07T03:59:59Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![skaverat](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/779978/32.png) [@skaverat](https://www.ruby-forum.com/u/skaverat)\
**Post date:** [July 7, 2008, 3:59am UTC](https://www.ruby-forum.com/t/problem-with-two-foreign-keys/142344/1 "2008-07-07T03:59:59Z")

</div>

so, I’m using following schema:

#Users#  
id  
nick

#Messages#  
id  
from\_user\_id  
to\_user\_id  
subject  
message

#user.rb  
has\_many :messages

#message.rb  
belongs\_to :to\_user, :class\_name =\> “User”  
belongs\_to :from\_user, :class\_name =\> “User”

assigning the userids to a message is no problem, but is there a way to  
collect all messages received by a user?  
like “user.messages” receives all messages with to\_user\_id = user.id?

---

<div class="post-metadata">

**Author:** ![skaverat](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/779978/32.png) [@skaverat](https://www.ruby-forum.com/u/skaverat)\
**Post date:** [July 7, 2008, 10:08am UTC](https://www.ruby-forum.com/t/problem-with-two-foreign-keys/142344/2 "2008-07-07T10:08:21Z")

</div>

On Jul 7, 2:59 am, Skave R. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> like “user.messages” receives all messages with to\_user\_id = user.id?  
> Your has\_many needs to use the :foreign\_key option. I put some  
> examples at  
> [Creating multiple associations with the same table - Space Vatican](http://www.spacevatican.org/2008/5/6/creating-multiple-associations-with-the-same-table)

Fred

---

<div class="post-metadata">

**Author:** ![skaverat](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/779978/32.png) [@skaverat](https://www.ruby-forum.com/u/skaverat)\
**Post date:** [July 7, 2008, 7:03pm UTC](https://www.ruby-forum.com/t/problem-with-two-foreign-keys/142344/3 "2008-07-07T19:03:06Z")

</div>

Frederick C. wrote:

> On Jul 7, 2:59ï¿½am, Skave R. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:
> 
> > like “user.messages” receives all messages with to\_user\_id = user.id?  
> > Your has\_many needs to use the :foreign\_key option. I put some  
> > examples at  
> > [Creating multiple associations with the same table - Space Vatican](http://www.spacevatican.org/2008/5/6/creating-multiple-associations-with-the-same-table)
> 
> Fred

thanks. I forgot to add the associations to user.rb - I just used  
has\_many :messages.

It works fine now
