0

Im new to Rails and actually im trying to write my own messaging application. So far i have many users with username, password, etc. And now im figuering out how i should best write the migration for the message model. I thought that a message needs:

Message

 sender_id => integer
 recipent_id => integer
 created_at => time
 updated_at => time

The first problem im facing is that of course sender_id is unique but what is with recipent_id, there are often messages that should go to several people!

Next problem is i dont know how i have to refer form the user model to the message model i mean normaly i would write:

User has_many :messages

Message belongs_to :user

To do this i would need a coulmn named user_id in the message model , but now i have two cloumns sender_id and reciepent_id!

I hope you can give my some hints! Thanks

Raziel
  • 444
  • 6
  • 22
John Smith
  • 6,105
  • 16
  • 58
  • 109

1 Answers1

2

Is this what you are looking for?

class User < ActiveRecord::Base
  has_many :messages, :foreign_key => "sender_id" #this only gives the messages sent by the user.
end

class Message < ActiveRecord::Base
  #sender_id
  belongs_to :sender, :class => "User", :foreign_key => "sender_id"
  has_many :recipients, :class => "MessageRecipient"
end

class MessageRecipient < ActiveRecord::Base
  belongs_to :message
  belongs_to :recipient, :class => "User", :foreign_key => "recipient_id"
end

If you want to get all the recipients for the message, you could do

message.recipients.collect(&:email)
usha
  • 28,973
  • 5
  • 72
  • 93
  • Thanks i will try it and when i have further questions i will come back to you! But for now thanks – John Smith Oct 23 '13 at 15:35
  • Maybe you can help me with this question: http://stackoverflow.com/questions/19606459/how-to-get-not-only-single-record-but-all-records-that-belong-to-specific-search – John Smith Oct 26 '13 at 12:02