Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between embeds_many and has_many in mongoid

Can anyone explain to me the difference between embeds_many and has_many in mongoid?

like image 283
enRai Avatar asked Jun 02 '12 05:06

enRai


People also ask

How to define one to many relationships 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.

How are embedded documents stored in Mongoid?

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.

What is has_many and belongs_to macros in Mongoid?

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.

Can a child embedded document belong to more than one type?

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.


1 Answers

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.

like image 125
Hck Avatar answered Sep 28 '22 12:09

Hck