views:

368

answers:

1

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

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

and then in the Message class I have

  belongs_to :user

The first relationship -- via user_id -- goes perfectly well. I haven't the slightest idea what to put in the Message class for the second relationship. The messages table is built with both user_id and receiver_id, so the support is there.

Is this even possible?

Also, then I'd have no idea how to get to the messages RECEIVED by a user... or the User who received a message :)

[I know that I can work around this by having a sender table and a receiver table and a messages table and maybe a bunch of other tables (a conversations table!), but I'd like to do it like this, for the fun of it. This application will be used for learning only.]

Also important: where would the docs be for this? This is not very helpful.

+6  A: 

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
THANKS @lotusvskoi... this is very cool.
Yar
Wow, that's cool: now each Message instance has a user (a User instance) and a receiver (also a User instance). I guess I'll have to go back and change them to a "sender" and receiver :)
Yar