Mongoid embeds_many:在不保存的情况下推送文档,以保留脏状态 [英] Mongoid embeds_many: push document without save in order to preserve dirty state

查看:68
本文介绍了Mongoid embeds_many:在不保存的情况下推送文档,以保留脏状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Mongoid中,将文档推入embeds_many关系会自动将文档持久保存到数据库中.通常,这很好,但是当我需要跟踪对嵌入式文档的更改时遇到了问题.

In Mongoid, pushing a document into an embeds_many relation automatically persists the document to the database. Normally, this is fine, but I run into problems when I need to track changes to the embedded document.

假设您有两个模型:

class List
  include Mongoid::Document
  embeds_many :items
  field :title
end

class Item
  include Mongoid::Document
  embedded_in :list
  field :name
end

.changes属性发生了这种情况:

This happens to the .changes attribute:

list = List.new(title: 'List title')
list.save  #list is now persisted
item = Item.new(name: 'Item name')
item.changes  #returns Hash with {'name' => [nil, 'Item name']}
list.items << item  #saves item to database under the hood
item.changes  #returns empty Hash, because item was autosaved with list

我可以使用item.previous_changes来检查在将项目推入列表之前所做的更改,但是在我的特定情况下,这会给我带来各种麻烦,以使事情易于管理.

I could use item.previous_changes to inspect the changes that were made before pushing the item into the list, but in my specific case, this would give me all kinds of troubles to keep things manageable.

我想要实现的是能够初始化Item文档,然后将其添加到list(通过<<push),而无需立即对其进行持久化.

What I would like to achieve, is to be able to initialize an Item document and then add it to list (via << or push) without persisting it immediately.

我知道Mongoid确实提供了建立embeds_many关系而不持久的选项(请参见 http://mongoid.org/en/mongoid/docs/relations.html#embeds_many ):

I'm aware that Mongoid does provide an option to set up embeds_many relations without persisting (see http://mongoid.org/en/mongoid/docs/relations.html#embeds_many):

list.items.build(name: 'Another item')

问题在于Mongoid为您创建了Item实例.在我的情况下,embeds_many关系中的文档可能是Item的子类(例如SpecialItem < Item),这与build不能很好地配合.但是,如果有人知道解决此限制的方法,我也很乐意接受它作为答案.

The problem there is that Mongoid creates the Item instance for you. In my case, the documents in the embeds_many relation may be subclasses of Item (e.g. SpecialItem < Item), which wouldn't work well with build. But if anyone knows of a way to get around this limitation, I'd also be happy to accept it as an answer.

推荐答案

要使用您的示例来跟踪构建子类"问题,您可以:

To follow up on the "building a subclass" issue using your example, you can:

list.items.build({
  name: "Another Item"
}, SpecialItem)

指定您想要Mongoid为您构建的(子)类.

To specify the (sub)class that you want Mongoid to build for you.

这篇关于Mongoid embeds_many:在不保存的情况下推送文档,以保留脏状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆