41

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

theTRON
  • 9,608
  • 2
  • 32
  • 46
enRai
  • 671
  • 6
  • 12

1 Answers1

65

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.

castis
  • 8,154
  • 4
  • 41
  • 63
Hck
  • 9,087
  • 2
  • 30
  • 25
  • 1
    when I have User and Post models can I embed only user name and id. to make a link for example to users profile. – Tolik Kukul Dec 22 '12 at 18:16
  • 9
    And I don't think `embeds_many` records can be found directly using the model e.g. Post.find(1). You have to find the parent record first, and then look for the child through the parent e.g. `user = User.find(1); user.posts.find(1)` – bigpotato Nov 24 '14 at 16:26
  • I just discovered this myself! I was using embeds many, when I should have been using has_many!! – Donato Mar 07 '15 at 20:44