Rails线程私有消息

我有以下两种型号:

class Message  'User' belongs_to :from_user, :class_name => 'User' has_ancestry #Using the 'ancestry' gem end class User  'Message', :foreign_key => 'to_user_id' has_many :messages_sent, :class_name => 'Message', :foreign_key => 'from_user_id' end 

允许每个用户与另一个用户进行一次对话,并且应该从原始消息中对所有回复进行线程化。

在我的“索引”控制器操作中,如何查询已发送的消息和收到的消息? 例如,如果User1命中’/ users / 2 / messages /’,他们应该看到user1和user2之间的整个对话(无论谁发送了第一条消息)。 我是否需要添加“线程”模型,或者有没有办法用我当前的结构来完成这个?

谢谢。

您可能最好将其重组为可以加入人员的对话,而不是链中的一系列互连消息。 例如:

 class Conversation < ActiveRecord::Base has_many :messages has_many :participants has_many :users, :through => :participants end class Message < ActiveRecord::Base belongs_to :conversation end class Participant < ActiveRecord::Base belongs_to :conversation belongs_to :user end class User < ActiveRecord::Base has_many :conversations has_many :participants end 

当消息发送给某人时,为其创建会话并通过将其添加到users列表来邀请相关方。

可以通过在Message本身或使用祖先建立父关系来添加线程消息传递,但在实践中这往往会过度杀死,因为对于大多数人来说,回复的简单时间顺序通常就足够了。

要跟踪读/未读状态,您需要直接在用户和消息之间建立关联表,这可能很棘手,因此除非您需要,否则请避免使用它。

请记住,某些名称由Ruby或Rails保留,而Thread是其中之一,因此您不能拥有具有该名称的模型。