Mongoid save is not performed without embedded_in relationship

I have one document embedded in another in Mongoid.

class A < B include Mongoid::Document embeds_one :shipping_address, class_name: 'Address' 

In my case, I missed the inverse ratio:

 class Address # embedded_in :A 

Why is this, although the API is working fine and fully as expected:

  address = A.address address.zip = 1234 a.changed? #true address.save a.changed? #false 

Is the document not actually saved ?

If I return the embedded_in statement, persistence really works fine.

+4
source share
2 answers

My understanding of the Mongolian source is not the best, so do not kick me in too tough mods.

I assume Mongoid is similar to ActiveRecord in this regard. In ActiveRecord, the definition :has_many does not modify the parent, but includes methods for accessing the child. belongs_to , on the other hand, pulls out foreign key management methods.

Looking at the source code for Mongoid, it seems that persistence is called from the inline class to the parent, and not vice versa ( source ). Removing embedded_in will remove additional methods for inserting the child into the parent.

Feel free to correct me if I am leaving :)

+2
source

Although you can win a lot when you decide to embed documents in MongoDB, you refuse the ability to request everything outside the context of the parent. If you want to be able to work with address documents independently of each other, outside the context of the parent document, you must link the documents with has_many instead of embedding with embeds_many . This is due to its own set of pros and cons.

If you decide to embed documents, you specify embedded_in in the model and gain access to the embedded documents as follows:

 a = A.new # Parent document a.addresses # Embedded Address documents 

( Link to documentation )

+1
source

Source: https://habr.com/ru/post/1443759/


All Articles