Mongoid 不持久关联
考虑以下情况:
class Parent
include Mongoid::Document
field:name
references_one :child
before_create :initialize_child
protected
def initialize_child
self.child = Child.create
end
end
class Child
include Mongoid::Document
field:name
referenced_in :parent
end
在控制台中,我得到以下奇怪的行为:
> p = Parent.create
=> #<Parent _id: 4d811748fc15ea355d00000b, name: nil>
> p.child
=> #<Child _id: 4d811748fc15ea355d00000c, name: nil, parent_id: BSON::ObjectId('4d811748fc15ea355d00000b')>
到目前为止一切都很好。现在,当我尝试获取父级,然后找到子级时 - 没有运气......
> p = Parent.last
=> #<Parent _id: 4d811748fc15ea355d00000b, name: nil>
> p.child
=> nil
这对我来说 mongoid rc6 和 rc7 都会发生
我做错了什么(我是 mongoid 的新手)还是这是一个错误?有什么解决方法吗?
谢谢!!
乔纳森
Consider the following:
class Parent
include Mongoid::Document
field:name
references_one :child
before_create :initialize_child
protected
def initialize_child
self.child = Child.create
end
end
class Child
include Mongoid::Document
field:name
referenced_in :parent
end
In a console, i get the following weird behavior:
> p = Parent.create
=> #<Parent _id: 4d811748fc15ea355d00000b, name: nil>
> p.child
=> #<Child _id: 4d811748fc15ea355d00000c, name: nil, parent_id: BSON::ObjectId('4d811748fc15ea355d00000b')>
All good so far. Now when I try to fetch the parent, and then find the child -- no luck ...
> p = Parent.last
=> #<Parent _id: 4d811748fc15ea355d00000b, name: nil>
> p.child
=> nil
This happens for me with both mongoid rc6 and rc7
Am I doing something wrong (I am new to mongoid) or this a bug? Any work arounds?
Thanks!!
Jonathan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于子文件未嵌入,因此它不会自动保存它自己。
也可以尝试
- 您可能希望子文件嵌入到父文档中。如果是这样,您需要切换到“embedded_in”
Since the child isn't embedded, it won't auto-save it on its own
Try
Also -- you may be expected the Child to be embedded in the Parent document. If so, you'll want to switch to "embedded_in"