4

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.

4

1 に答える 1

11

Userクラスの場合:

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

メッセージクラス:

belongs_to :user
belongs_to :receiver, :class_name => "User"


@user = User.first
@user.messages
@user.received_messages
于 2009-01-30T23:34:49.913 に答える