views:

33

answers:

1

I want to implement a messaging system for my app.

I have users.

What exactly should I do? create a messages model with foreign two user foreign keys??.. what would be the most approproate way of getting this done?

My worry is that if I query "message.user" I wont know if Id be getting the sender of the receiver of the message

+3  A: 

Use two separate foreign keys with approprately named belongs_to relations to distinguish between senders and receivers.

Given a message model with the foreign keys sender_id and receiver_id you can do:

class Message < ActiveRecord::Base
  belongs_to :sender, :class_name => "User", :foreign_key => "sender_id"
  belongs_to :receiver, :class_name => "User", :foreign_key => "receiver_id"
end

Now you'll be able to reference a message's sender using message.sender and receiver using message.receiver.

Pär Wieslander