Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen to use Embedded Documents?
    primarykey
    data
    text
    <p>I am trying to figure out how to layout my database for a site I am working on. Here are my models:</p> <pre><code>class User include MongoMapper::Document // keys here many :items many :likes end class Item include MongoMapper::Document key :name, String, :required =&gt; true many :likes end class Like include MongoMapper::EmbeddedDocument key :user_id, String, :required =&gt; true end </code></pre> <p>I believe the <code>Like</code> should be embedded somewhere, but I am having a hard time picking one because of the functionality I would like to get out of it.</p> <pre><code>user = User.first user.likes // should print out all the Items he liked item = Item.first item.likes // so I can count how many people like that item </code></pre> <p>Although the problem comes when using an EmbeddedDocument, you lose the <code>find</code>, and other helpful methods, and you can't have it embedded in both models. So having it only in <code>Item</code>, I would need to run this (but can't):</p> <pre><code>item = Item.first item.likes.find_by_user_id(User.first._id) </code></pre> <p>undefined method <code>find_by_user_id</code> will be thrown. So if I was to embed this into my <code>User</code>, I still couldn't do this.</p> <pre><code>likes = Like.all // will throw undefined `all` </code></pre> <p>So I came to the conclusing to maybe do it this way:</p> <pre><code>class Like include MongoMapper::Document key :user_id, String, :required =&gt; true key :item_id, String, :required =&gt; true belongs_to :user belongs_to :item end </code></pre> <p>But this seems like I am still trying to do things the old MySQL way. Could anybody give me a point on the most likely way to code this with MongoMapper?</p> <p>Thanks in advance!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload