Reputation: 640
I'm slowly getting crazy with this problem. I'm pretty sure it is something trivial and I have misunderstood something as I am just beginning my journey with Mongoid (and Ruby on Rails).
My model is the following:
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
The User model "embeds_many" Drawings, the Painting model "embeds_one" template_drawing and result_drawing.
What I have been trying to do for the past couple of hours is to create a new Drawing, attach it to a user and define its parent if it has one. I have been playing around in the console a lot but basically what I was doing was similar to this:
User.first.drawings.last.parent_drawing = User.first.drawings.first.dup
Although the console seems happy and returns the content of User.first.drawings.first, User.first.drawings.last.parent_drawing returns nil...
I have tried to assign them to variables and assign variables etc. But nothing changes. I have tried to create new Drawings and put one as the parent of the other also unsuccessfully.
I came to the conclusion that assigning the parent wouldn't be possible. So I tried to do the other way round and add a child, but I still don't get an object with a parent or a child.
Here's some more code that fails (extracted and shortened from my Rails code):
drawing = Drawing.new({:user => @user})
drawing.parent_drawing = @user.drawings.find(parent_id).dup
drawing.save
Funnily, the drawing itself is saved and listed in user.drawings, but doesn't have a parent.
What am I doing wrong?
Upvotes: 2
Views: 951
Reputation: 640
Taking the advice in the comments I tried to re-think my models from scratch. I reread the doc on polymorphic relationships and made Drawing polymorphic. Still a Drawing should be able to be embedded within another Drawing and recursively embedded led nowhere again.
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.
Upvotes: 2