Peter Ehrlich
Peter Ehrlich

Reputation: 7135

Mongoid save fails silently without embedded_in relation

I have one document embedded in another in Mongoid.

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

I have, in my case, omitted the inverse relation:

class Address
   # embedded_in :A

Why is it, that although the API works fine and completely as expected:

 address = A.address
 address.zip = 1234

 a.changed? #true

 address.save

 a.changed? #false

The document is not actually saved?

If i return the embedded_in statement, the save actually works fine.

Upvotes: 4

Views: 693

Answers (2)

platforms
platforms

Reputation: 2726

While you can gain a lot when you choose to embed documents in MongoDB, you do give up the ability to query everything outside of the context of the parent. If you want to be able to work with Address documents independently, outside of the context of the parent document, you should link documents with has_many instead of embedding with embeds_many. This comes with it's own set of pros and cons.

If you choose to embed documents, you do specify embedded_in in the model and you access the embedded documents like this:

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

( Documentation Reference )

Upvotes: 1

Tsagadai
Tsagadai

Reputation: 887

My understanding of the Mongoid source is not the best so don't kick me too hard mods.

I assume that Mongoid is similar to ActiveRecord in this regard. With ActiveRecord, defining a :has_many does not change the parent object but includes methods for accessing the child. belongs_to on the other hand pulls methods for managing foreign keys.

Looking at the source code for Mongoid it seems that persistence is called from the embedded class to the parent and not the other way around (source). Removing the embedded_in would remove the additional methods for inserting the child into the parent.

Feel free to correct me if I am way off :)

Upvotes: 2

Related Questions