ROR model associations problem
I have models User and Message. Every user can send messages to other users. In User there are no fields related to the Message. In Message there are the following: from_id, to_id, content.
I was trying to work it myself, but got confused after a few minutes.
What combination of has_many has_one, belongs_to should I use in each model? There should be the following methods available:
msg.from => author of the message
msg.to => receiver
usr.sent_messages => array of sent messages
usr.received_messages => array of received messages
Moreover I want the message to be destroyed when either sender or receiver is destroyed. So :dependent=>:destroy is needed somewhere
This are my attempts, which of course don't work:
User:
has_many :sent_messages, :source => :message, :dependent => :destroy
has_many :received_messages, :source => :message, :dependent => :destroy
Message:
has_one :from, :source=>:user
has_one :to, :source开发者_Python百科=>:user
Thanks in advance,
Bye
You could do it like this:
## User
has_many :received_messages, :foreign_key => :to_id, :class_name => 'Message', :dependent => :destroy
has_many :sent_messages, :foreign_key => :from_id, :class_name => 'Message', :dependent => :destroy
## Message
belongs_to :from, :class_name => 'User', :foreign_key => :from_id
belongs_to :to, :class_name => 'User', :foreign_key => :to_id
Just remember that when doing associations, when you do a belongs_to it means that the object that belongs is a weak entity, so it has to contain the foreign key, when you say has_one or has_many, the object that has is the strong entity so it does not contain the foreign key.
Think about it by the existence idea, if an object can exist without it's association, it's a strong entity, if it can't exist without it, it's a weak one.
精彩评论