views:

106

answers:

1

I am trying to make a private messaging system, where you send a message to one or more users. Now the messages schema is like

user_id, to_id, msg

How do i make the associations so that i can get the details of the sender and the recipient?

A: 

schema:

sender_id recipient_id

class Message
  belongs_to :sender, :class_name => 'User'
  belongs_to :recipient, :class_name => 'User'
end


class User
  has_many :sent_messages, :class_name => 'Message', :foreign_key => :sender_id
  has_many :income_messages, :class_name => 'Message', :foreign_key => :recipient_id
end
fantactuka
i have done smthng similar, but i cannot get the values of the user's attributes.I used msg = Message.find(:all)<%= msg.sender.name %>and it says, undefined method `name` for nil:NilClass
Amit
nvm, i got it to work, had to add foreign_key to the Message class too, like soclass Message belongs_to :sender, :class_name => 'User', :foreign_id => :sent_by belongs_to :recipient, :class_name => 'User', :foreign_id => :sent_toend
Amit
can you show the code?
fantactuka