use*_*752 5 messaging inheritance chat ruby-on-rails ruby-on-rails-3
我有以下两种型号:
class Message < ActiveRecord::Base
belongs_to :to_user, :class_name => 'User'
belongs_to :from_user, :class_name => 'User'
has_ancestry #Using the 'ancestry' gem
end
class User < ActiveRecord::Base
has_many :messages_received, :class_name => 'Message', :foreign_key => 'to_user_id'
has_many :messages_sent, :class_name => 'Message', :foreign_key => 'from_user_id'
end
Run Code Online (Sandbox Code Playgroud)
允许每个用户与另一个用户进行一次对话,并且应该从原始消息中对所有回复进行线程化.
在我的"索引"控制器操作中,如何查询已发送的消息和收到的消息?例如,如果User1命中'/ users/2/messages /',他们应该看到user1和user2之间的整个对话(无论谁发送了第一条消息).我是否需要添加"线程"模型,或者有没有办法用我当前的结构来完成这个?
谢谢.
tad*_*man 16
您可能最好将其重组为可以加入人员的对话,而不是链中的一系列互连消息.例如:
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
Run Code Online (Sandbox Code Playgroud)
向某人发送消息时,请为其创建对话,并通过将其添加到users
列表中来邀请相关方.
可以通过在Message本身或使用祖先建立父关系来添加线程消息传递,但在实践中这往往会过度杀死,因为对于大多数人来说,回复的简单时间顺序通常就足够了.
要跟踪读/未读状态,您需要直接在用户和消息之间建立关联表,这可能很棘手,因此除非您需要,否则请避免使用它.
请记住,某些名称由Ruby或Rails保留,并且Thread
是其中之一,因此您不能拥有具有该名称的模型.