使用mongodb将消息回复与mongodb一起嵌入到消息父中 [英] Embedding message replies inside message parent with mongodb using mongoid
问题描述
我认为将对特定消息的回复嵌入消息中是一种最佳实践,我正在尝试使用mongoid来实现它.这就是我所拥有的
I think it's a best practice to embed replies to a specific message inside that message and I'm trying to implement it using mongoid. here is what I have
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
这是我尝试定义消息及其回复关系的部分:
here is the part where I try to define the message and its replies relation:
embeds_many :replies, :class_name => 'Message'
embedded_in :message, :inverse_of => :replies
这对我不起作用,我也不知道为什么,我知道该怎么做?
it's not working for me and I don't know why, any idea how I can do such a thing?
推荐答案
是否最佳实践是一个值得商de的话题.例如,您必须注意对象的大小限制(当前为4 MB,但很快就会增加).
Whether it is best practice or not is a highly debatable topic. For instance, you have to mind the object size limit (currently 4 MB, but will go up soon).
关于您的问题: 我建议您更改
as for your question: I suggest that you change
embeds_many :replies, :class_name => 'Message'
embedded_in :message, :inverse_of => :replies
到
embeds_many :replies, :class_name => 'Message'
referenced_in :message
您还必须手动指定两个连接(这应该没问题,因为它们可能始终是不变的).
And you will also have to specify both connections manually (that should not be a problem, as they are probably immutable anyway).
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
这篇关于使用mongodb将消息回复与mongodb一起嵌入到消息父中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!