我计划在成员之间实现私人消息系统.我想知道什么是首选方法.
要求是
>我应该能够像这样轻松地检索它们
@user.conversations #Should return User objects that I sent or received messages from (but not me) @user.conversations.messages #Messages from all or specific user objects. @user.conversations.messages.unread #Unread messages
>当调用@ user.conversations时,应仅检索向我发送消息的人或发送消息的人.应排除current_user.
>如果我是sender_id = 5并发送to_id = 10那么,另一个人将回复发件人= 10 to_id = 5.这应该被视为并理解为相同的会话对象.
关于最后一点.我不确定什么是建模的首选方法.
最好使用一个Conversation模型来处理所有消息,例如
attr_accessible :user_id,:friend_id,:message,:read belongs_to :user
或者,最好创建一个Conversation模型来处理关联和消息的Message模型.
我想看看如何实现这种关系的示例,以及是否有其他方法可以实现.
我在这里有点迷失.
解决方法
一个更简单的模型是捕获每个消息:
class Message < ActiveRecord::Base belongs_to :from_user,:class_name => 'User' # from_user_id field fk Users belongs_to :to_user,:class_name => 'User' # to_user_id field fk Users belongs_to :thread,:class_name => 'Message' # Reference to parent message has_many :replies,:class_name => 'Message',:foreign_key => 'thread_id' named_scope :in_reply_to,lambda { |message| :conditions => {:thread => message},:order => 'created_at' } end class User < ActiveRecord::Base has_many :messages_received,:foreign_key=> 'to_user_id' has_many :messages_sent,:foreign_key=> 'from_user_id' end
如果您需要捕获消息线程,那么任何回复消息都可以存储对开始对话(又称为线程)的初始消息的引用.例如:
first_msg = Message.new(:to_user => bob,:from_user => sally,:body => 'Hello!') sally_reply = first_msg.replies.build(:to_user => bob,:body => 'hi back') bob_reply = first_msg.replies.build(:to_user => sally,:from_user => bob,:body => 'later')