2

我对这个问题慢慢变得疯狂。我很确定这是一件微不足道的事情,我误解了一些事情,因为我刚刚开始使用 Mongoid(和 Ruby on Rails)。

我的模型如下:

class Drawing
include Mongoid::Document

    field :image_uid
    image_accessor :image
    field :date_created, type: Time, default: Time.now

    recursively_embeds_many

    embedded_in :user
    embedded_in :painting_template, class_name: 'Painting', inverse_of: :template_drawing
    embedded_in :painting_result, class_name: 'Painting', inverse_of: :result_drawing

用户模型“embeds_many”图纸,绘画模型“embeds_one”template_drawing 和result_drawing。

在过去的几个小时里,我一直在尝试做的是创建一个新的绘图,将其附加到用户并定义其父级(如果有的话)。我一直在控制台中玩耍,但基本上我所做的与此类似:

User.first.drawings.last.parent_drawing = User.first.drawings.first.dup

虽然控制台看起来很开心并返回了 User.first.drawings.first 的内容,但 User.first.drawings.last.parent_drawing 返回 nil...

我试图将它们分配给变量并分配变量等。但没有任何改变。我曾尝试创建新图纸并将其中一个作为另一个的父级,但也未成功。

我得出的结论是,分配父母是不可能的。所以我尝试反过来添加一个孩子,但我仍然没有得到一个有父母或孩子的对象。

这里还有一些失败的代码(从我的 Rails 代码中提取和缩短):

drawing = Drawing.new({:user => @user})
drawing.parent_drawing = @user.drawings.find(parent_id).dup
drawing.save

有趣的是,绘图本身已保存并列在 user.drawings 中,但没有父级。

我究竟做错了什么?

4

1 回答 1

2

接受评论中的建议,我试图从头开始重新思考我的模型。我重新阅读了有关多态关系的文档,并使绘图具有多态性。仍然一个绘图应该能够嵌入到另一个绘图中,并且递归嵌入再无处可寻。

With the doc/code of Mongoid about cyclic relationships (http://rdoc.info/github/mongoid/mongoid/Mongoid/Relations/Cyclic/ClassMethods) I suspected it was because the embeddings "recursively_embeds_many" is doing were wrong because they didn't include the fact that Drawing was polymorphic!

Given that the embedded_in statement is made by the fact that it is polymorphic, adding

embeds_one :base_drawing, class_name: "Drawing", as: :drawable, cyclic: true

seemed to have the effect I was looking for. It won't include "children" as "recursively_embeds_many" would have done, but it's not necessary in my case.

I hope this helps the next person having trouble with recursively embedded polymorphic relationships.

于 2012-08-14T12:45:38.297 回答