Model with 2 foreign keys

Hi All,
I’d like to integrate a simple user-oriented messaging system into my
app.
I have a Message model, with :from_user_id, and :to_user_id (for the
user that sent and the user that recieved the message).

Obivously, (User) has_many :messages will fetch the messages that a
certain user has created, but not the ones that they have been sent.

Currently, I have this:
has_many :messages, :foreign_key=>:to_user_id
has_many :sent_messages, :class_name=>‘Message’,
:foreign_key=>:from_user_id

So I have to get all the messages with 2 separate calls(and sets of
queries). This doesn’t seem quite right to me, and was wondering if
there is a better way.

Is it possible to retrieve all messages for a user (recieved AND sent)
in 1 relationship?

Many thanks for reading.

Paul O. wrote in post #1046790:

Hi All,
I’d like to integrate a simple user-oriented messaging system into my
app.
I have a Message model, with :from_user_id, and :to_user_id (for the
user that sent and the user that recieved the message).

Obivously, (User) has_many :messages will fetch the messages that a
certain user has created, but not the ones that they have been sent.

Currently, I have this:
has_many :messages, :foreign_key=>:to_user_id
has_many :sent_messages, :class_name=>‘Message’,
:foreign_key=>:from_user_id

So I have to get all the messages with 2 separate calls(and sets of
queries). This doesn’t seem quite right to me, and was wondering if
there is a better way.

Is it possible to retrieve all messages for a user (recieved AND sent)
in 1 relationship?

There’s potentially a few different ways to accomplish this. I would
probable just create a simple one-to-many associations and add a
message_type column to the messages table.

User

has_many :messages

Message

belong_to :user

Then just add a couple of scopes to the model: received & sent.

my_user.messages.received
my_user.messages.sent
my_user.messages

class Message < ActiveRecord::Base
scope :received, where(:message_type => ‘received’)
scope :sent, where(:message_type => ‘sent’)
end

http://api.rubyonrails.org/classes/ActiveRecord/Scoping/Named/ClassMethods.html#method-i-scope

Thanks for the reply, Robert - I’ll try with that approach too.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs