nacho10f
nacho10f

Reputation: 5886

help with rails associations

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

Upvotes: 2

Views: 96

Answers (1)

Pär Wieslander
Pär Wieslander

Reputation: 28934

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.

Upvotes: 3

Related Questions