Re: Multiple relations between two models

Thorsten L
Wed, 18 Oct 2006 13:21:42 -0000

Well i thought about this issue too sometime ... and though i''m
perfectly sure, this could work:

class Message < ActiveRecord::Base
    belongs_to :sender, :foreign_key => "sender_id", :class =>
"User"
    belongs_to :recipient, :foreign_key => "recipient_id", :class
=>
"User"
end


class User  < ActiveRecord::Base
   has_many :sentmessages, :foreign_key => "sender_id", :class
=>
"Message"
   has_many :rcvdmessages, :foreign_key => "recipient_id", :class
=>
"Message"
end

Then you *should* be able to do:

somevariable = message.sender
somevariable = message.recipient

sentmsgs = user.sentmessages.find :all
rcvdmsgs = user.rcvdmessages.find  :all

So you practically reference the other class twice in both Models, but
with different assiciation names (:sender <-> :recipient and
:sentmessages <-> :rcvdmessages) and foreig keys ( sender_id <->
recipient_id).
That creates two different associations with the same Model ....
Someone please correct me if i''m wrong, i never tested it and only made
my own thoughts from the rails docs

As i want to use soemthing like this myself soon, and IF the above is
correct, i want to ask:

How is the best way to store the messages twice, so sender + recipient
can both keep a copy and delete it whenever they want?
Anyone got any idea?