Two foreign keys with ActiveRecord? [rails]

I have a User class with a reference to the Message class. The message class has user_id (which is the sender) and receiver_id . Therefore, in the User class, I

  has_many :messages has_many :messages, :foreign_key => "receiver_id" 

and then in the message class I have

  belongs_to :user 

The first relation - through user_id - goes fine. I have no idea what to add the Message class to the second relationship. The message table is built with both user_id and receiver_id , so support exists.

Is it possible?

In addition, I would not know how to get to messages received by the user ... or the user who received the message :)

[I know that I can get around this by having a sender table and a recipient table, a message table, and possibly a bunch of other tables (a conversation table!), But I would like to do it this way for fun. This app will only be used for training.]

It is also important: where will the documents be for this? This is not very helpful.

+4
source share
1 answer

In your User class:

 has_many :messages has_many :received_messages, :foreign_key => "receiver_id", :class_name => "Message" 

In your message class:

 belongs_to :user belongs_to :receiver, :class_name => "User" @user = User.first @user.messages @user.received_messages 
+11
source

All Articles