Geo
Geo

Reputation: 96767

How should this model be designed?

In a Rails app, I want to allow users to send messages from one to another. So, I have a User model that will have this:

has_many :messages

I was thinking that the Message model will have a from field, containing the id of the user that sent it, and a to field, containing the user id of the user that it's addressed to. What would be the best practice for the Messsage model? Should I generate it like this:

rails g model Message from:integer to:integer title:string content:text

How would I associate it to a user? Should I associate it to 2 users, since the from and to fields reference existing users? How would I represent this relationship? What kind of relationship would I write in the message model? belongs_to :user ?

I feel there should be a way of letting Rails manage the user id's for me, so that I don't have to create integer fields myself.

Upvotes: 1

Views: 118

Answers (2)

Ashish
Ashish

Reputation: 5791

User

has_many :sent_messages, :class_name => "Message", :foreign_key => 'from'
has_many :received_messages, :class_name => "Message", :foreign_key => 'to'

Message

belongs_to :sender, :class_name => 'User', :foreign_key => 'from'
belongs_to :receiver, :class_name => 'User' :foreign_key => 'to'

Upvotes: 6

Jarrett Meyer
Jarrett Meyer

Reputation: 19573

If you want both you should probably do something like this

has_many :sent_messages, :class_name => 'Message', :foreign_key => 'from'
has_many :received_messages, :class_name => 'Message', :foreign_key => 'to'

This is similar to this question: Rails Model has_many with multiple foreign_keys

Upvotes: 2

Related Questions