Rails 线程式私人消息传递
我有以下两种模型:
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
每个用户都可以与另一用户进行一次对话,并且所有回复都应该从原始消息中进行线程化。
在我的“索引”控制器操作中,如何查询发送的消息和接收的消息?例如,如果 User1 点击“/users/2/messages/”,他们应该看到 user1 和 user2 之间的整个对话(无论谁发送了第一条消息)。我是否需要添加“线程”模型,或者有没有办法用我当前的结构来完成此任务?
谢谢。
I have the following two models:
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
Each user is allowed to have one conversation with another user and all the replies should be threaded from the original message.
In my 'index' controller action how do I query both sent messages and received messages? For example, if User1 hits '/users/2/messages/' they should see the whole conversation between user1 and user2 (regardless of who sent the first message). Do I need to add a 'Thread' model or is there a way to accomplish this with my current structure?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您最好将其重组为可以与人们一起参与的对话,而不是一系列相互关联的消息链。例如:
当向某人发送消息时,为其创建一个对话,并通过将适当的各方添加到
用户
列表来邀请他们。可以通过在消息本身中构建父关系或使用祖先来添加线程消息传递,尽管在实践中这往往是过度的,因为简单的回复时间顺序通常对大多数人来说就足够了。
要跟踪已读/未读状态,您将需要直接在用户和消息之间建立关联表,这可能很棘手,因此除非需要,否则请避免使用它。
请记住,某些名称是由 Ruby 或 Rails 保留的,
Thread
就是其中之一,因此您不能拥有具有该名称的模型。You may be better off restructuring this as a conversation to which you can join people than a series of interconnected messages in a chain. For instance:
When a message is sent to someone, create a conversation for it and invite the appropriate parties by adding them to the
users
list.Threaded messaging could be added here by building a parent relationship into the Message itself or using ancestry, though in practice this tends to be over-kill as simple chronological ordering of replies is usually sufficient for most people.
To track read/unread status you will need an association table between user and messages directly, and this can be tricky, so avoid it unless you need it.
Keep in mind that some names are reserved by either Ruby or Rails, and
Thread
is one of them, so you can't have a model with that name.