Re: Multiple relations between two models

Stewart
Wed, 18 Oct 2006 15:51:55 -0000

Thorsten L wrote:
> 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?

i like your suggestion. Bala what your suggesting is easy and thats what
i was going to go with but that would require more code than i would
like in the view....

I worked it out with the help of the api

class Message < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :title, :body
  belongs_to :sender, :class_name => "User", :foreign_key =>
"user_id"
end

thats all i had to do. For the record the hash is :class_name not :class

Also... the first hash you pass the belongs_to method must match the key
in the current model your dealing with.

So problem solved thanks for that...

I looked in to it a bit more and i am finding you can do a lot with the
model... such as this,

has_many :users, :order => "last_name"

now when ever i list the users its always in alpha...

how easy is that!