Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two foreign keys with ActiveRecord? [rails]

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.

like image 749
Dan Rosenstark Avatar asked Dec 22 '22 13:12

Dan Rosenstark


1 Answers

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
like image 84
assplecake Avatar answered Jan 06 '23 01:01

assplecake