Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create nested ResourceCollections in ember-resource - is this the correct way to do it?
    text
    copied!<p>I am currently working on an application using ember.js, ember-resource and couchdb.</p> <p>In my data model I have some nested resources, e. g.</p> <pre><code>MyApp.Task = Ember.Resource.define({ url: '/tasks', schema: { id: String, _rev: String, title: String, description: String, comments: { type: Ember.ResourceCollection, itemType: 'MyApp.Comment', nested: true } }); MyApp.Comment = Ember.Resource.define({ url: null, schema: { created: Date, start: Number, end: Number, text: String } }); </code></pre> <p>Everything works fine as long as I initially provide a "complete" model in the database, i. e. a task with an empty comment model. In this case, I am able to add comments to the task with</p> <pre><code> var newComment = MyApp.Comment.create({ created: created, start: start, end: end, text: text }); var comments = task.get('comments'); comments.pushObject(newComment); </code></pre> <p>However, my initial <code>task</code> data doesn't have the embedded <code>comments</code>, so I have to create the <code>Ember.ResourceCollection</code>for the nested comments programmatically.</p> <p>I have tried different approaches and tried to find some code in the ember-resource specs, but none of my attempts worked.</p> <p>My latest approach was</p> <pre><code>var comments = this.get('comments'); if (!comments) { comments = Ember.ResourceCollection.create({type: MyApp.Comment, content: []}); this.set('comments', comments); } comments.pushObject(newComment); </code></pre> <p>but this also doesn't work.</p> <p>So my question is: How can I create a nested model structure in <code>ember-resource</code> and save it to the database?</p> <p>Thanks a lot for any hint!</p> <hr> <p><strong>UPDATE:</strong></p> <p>After browsing through the source of <code>ember-resource</code> I figured out one way to solve my problem:</p> <pre><code>var comments = this.get('comments'); if (!comments) { this.updateWithApiData({comments: []}); comments = this.get('comments'); } comments.pushObject(newComment); </code></pre> <p>The method <code>updateWithApiData</code> seems to be the one used when reading the data from REST resources.</p> <p>I still wonder if this is the best / correct way to do it.....</p>
 

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