Can anyone explain to me the difference between embeds_many
and has_many
in mongoid?
One to many relationships where the children are stored in a separate collection from the parent document are defined using Mongoid's has_many and belongs_to macros. This exhibits similar behavior to Active Record.
Documents that are embedded using the embeds_one macro are stored as a hash inside the parent in the parent's database collection. You can optionally tell Mongoid to store the embedded document in a different attribute other than the name, by providing a :store_as option.
This persists the child immediately if executing from the parent, and persists the parent if executed from the child. One to many relationships where the children are stored in a separate collection from the parent document are defined using Mongoid's has_many and belongs_to macros. This exhibits similar behavior to Active Record.
When a child embedded document can belong to more than one type of parent document, you can tell Mongoid to support this by adding the as option to the definition on the parents, and the polymorphic option on the child. On the child object, an additional field will be stored that indicates the type of the parent.
embeds_many
is used to store relative documents inside of parent document.
has_many
is used to store a relation between documents in separate collections. Relative records of has_many
have field that stores id of the parent document.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With