Multiple foreignkeys for same model with different meaning (User.received_messages / User.sent_mess


#1

Hello,

I have 2 models: User and Message

Message:
belongs_to :sender, :class_name=>‘User’, :foreign_key=>‘sender_id’
belongs_to :receiver, :class_name=>‘User’, :foreign_key=>‘receiver_id’

// MESSAGE-MIGRATION START
create_table :messages do |t|
t.integer :sender_id
t.integer :receiver_id
t.string :subject
t.text :content

  t.timestamps
end

// MIGRATION END

User:
has_many :sent_messages, :class_name => “Message”, :foreign_key =>
“sender_id”
has_many :received_messages, :class_name => “Message”, :foreign_key
=> “receiver_id”

I want to access User.messages, because I need it for the destroy-
action -> User.messages.find(params[:id])

Can anyone help me?
Thanks!


#2

Hmmm…

It worked with:

has_many :friendships, :class_name => “Friendship”, :foreign_key =>
“sender_id = #{self.id} or friendships.receiver_id = #{self.id} AND 1”

But thats not very nice…!!! Is there a better solution??


#3

On Mar 3, 7:50 pm, Lp removed_email_address@domain.invalid wrote:

I want to access User.messages, because I need it for the destroy-
action -> User.messages.find(params[:id])

You want a single association that covers both sent and received
messages ? AFAIL there is no way to get an association to do that
(although you could construct a named scope that did).

Fred


#4

Hm, I tried it with named scopes, but

User.rb:

named_scope :messages, :join => :messages, :conditions = [“sender_id
= ? or receiver_id = ?”, self.id, self.id]

returns the collection of USERS -> not messages!

Or is there chance to get the messages?


#5

On Mar 3, 8:02 pm, Lp removed_email_address@domain.invalid wrote:

Hm, I tried it with named scopes, but

User.rb:

named_scope :messages, :join => :messages, :conditions = [“sender_id
= ? or receiver_id = ?”, self.id, self.id]

returns the collection of USERS -> not messages!

Or is there chance to get the messages?

You’d have to put the scope on Message class if you want it to return
messages ie
named_scope :for_user, lambda {|u| :conditions => [“sender_id = ? or
received_id = ?”, u,u]}

Then Message.for_user(bob) returns a scope for bob’s messages. You
could define a messages method on user to make this flow slightly
nicer ie

def messages
Message.for_user(self)
end

Fred


#6

Cool, thx!

Nice idea…