Mongoid store_in产生随机结果 [英] Mongoid store_in produces random results
问题描述
我正在使用Rails 3.2.2和mongoid 2.4.6。为了保持我的集合小,我使用store_in语句将子对象存储在sepparate集合中的基类中。我的代码如下所示:
I am using Rails 3.2.2 with mongoid 2.4.6. In order to keep my collections small I am storing child objects to a base class in sepparate collections using the "store_in" statement. My code looks like this:
class BaseClass
include Mongoid::Document
end
class ChildClass1 < BaseClass
store_in :child_1
end
class ChildClass2 < BaseClass
store_in :child_2
end
看来对象随机存储在或或其他儿童集合。 Child1类型的对象有时会存储在集合Child2中。
以下是我在日志中看到的令人惊讶的事情:
It appears that the objects get randomly stored in or or the other child collection. An object of type Child1 sometimes gets stored in collection Child2. Here is the surprising thing that I see in my logs:
Started POST "/child_class_1" for 127.0.0.1 at 2012-05-22 10:22:51 -0400
Processing by ChildClass1Controller#create as HTML
MONGODB (0ms) myproject_development['child_2'].insert....
这是从哪里来的?这是mongoid,rails还是mongodb中的一个错误?
Where does that come from? Is this a bug in mongoid, rails or mongodb?
推荐答案
我花了一段时间但我想出了答案。我决定发布它,希望它能帮助其他人。
It took me a while but I figured the answer out. I decided to post it, hoping it will help others.
Mongoid实现了一种叫做单表继承的东西。只要从父类派生子类,子项就会存储在父集合中,并添加type属性。使用store_in可以明确地告诉mongodb将文档存储在哪个集合中。在子类中定义store_in会使mongoid存储给定集合中的所有内容(包括父项)。我想使用一个专门的store_in任务为每个孩子混淆mongoid up。但是,结果是文档被随机存储在任何给定集合中。
Mongoid implements something that is called "single table inheritance". As soon as you derive a child class from a parent class, the child would be stored in the parent collection adding a "type" attribute. Using "store_in" tells mongodb explicitly which collection to store documents in. Defining the store_in in the child class makes mongoid store everything (incl. the parent) in the given collection. I guess using a dedicated store_in assignments for each child messes mongoid up. However, the result is that documents get stored randomly in any of the given collections.
这可以在Ruby中使用模块作为mixin来解决,以实现常见功能。这在这份文件。
This can be solved in Ruby using a module as mixin for the common functionality. This is described pretty well in this document.
但我终究决定不这样做了!我想要这个的原因是为了保持我的收藏量小,希望获得更好的性能。在与一些(10gen)专家交谈后,我认为更好的方法是对所有子元素使用单父对象集合。应该对mongodb的性能没有影响,但解决方案变得更加灵活。事实上,这可以更好地利用mongodb中的无模式设计。
因此代码将再次显示如下:
So the code will look like this again:
class BaseClass
include Mongoid::Document
... shared functionality
end
class ChildClass1 < BaseClass
...individual functionality...
end
class ChildClass2 < BaseClass
...individual functionality...
end
这篇关于Mongoid store_in产生随机结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!