我认为最好的做法是将回复嵌入到该消息中的特定消息中,并且我正在尝试使用mongoid来实现它。这就是我所拥有的
class Message
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Paranoia
field :subject
field :body
field :sender_deleted, :type => Boolean, :default => false
field :recipient_deleted, :type => Boolean, :default => false
field :read_at, :type => DateTime
referenced_in :sender, :class_name => "User", :inverse_of => :sender, :foreign_key => 'sender_id'
referenced_in :recipient, :class_name => "User", :inverse_of => :recipient, :foreign_key => 'recipient_id'
embeds_many :replies, :class_name => 'Message'
embedded_in :message, :inverse_of => :replies
这是我尝试定义消息及其回复关系的部分:
embeds_many :replies, :class_name => 'Message'
embedded_in :message, :inverse_of => :replies
它不适合我,我不知道为什么,不知道我怎么能做这样的事情?
答案 0 :(得分:3)
这是否是最佳实践是一个备受争议的话题。例如,您必须考虑对象大小限制(目前为4 MB,但很快就会上升)。
至于你的问题: 我建议你改变
embeds_many :replies, :class_name => 'Message'
embedded_in :message, :inverse_of => :replies
到
embeds_many :replies, :class_name => 'Message'
referenced_in :message
而且您还必须手动指定两个连接(这应该不是问题,因为它们可能无论如何都是不可变的。)
irb(main):002:0> msg1 = Message.new :subject => 'new question'
=> #<Message _id: 4cc7699f457601d7e8000001, created_at: nil, body: nil, updated_at: nil, subject: "new question", read_at: nil, sender_deleted: false, message_id: nil, recipient_deleted: false>
irb(main):003:0> msg2 = Message.new :subject => 'first comment'
=> #<Message _id: 4cc769b6457601d7e8000002, created_at: nil, body: nil, updated_at: nil, subject: "first comment", read_at: nil, sender_deleted: false, message_id: nil, recipient_deleted: false>
irb(main):005:0> msg2.message = msg1
=> #<Message _id: 4cc7699f457601d7e8000001, created_at: nil, body: nil, updated_at: nil, subject: "new question", read_at: nil, sender_deleted: false, message_id: nil, recipient_deleted: false>
irb(main):007:0> msg1.replies << msg2
=> [#<Message _id: 4cc769b6457601d7e8000002, created_at: nil, body: nil, updated_at: nil, subject: "first comment", read_at: nil, sender_deleted: false, message_id: BSON::ObjectId('4cc7699f457601d7e8000001'), recipient_deleted: false>]
irb(main):008:0> msg1.save
=> true