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.
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'
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
精彩评论