jeudi 23 février 2017

Objects in Ember Data

This has been asked a couple times, but the examples didn't help a whole lot.

I want to post 'posts' to my server, so I have a 'posts' model and then a 'single' model. The 'posts' model represents all the posts, and then my 'single' model represents what each post needs... I am new to Ember.js, and really could use a hand here/direction.

So when I submit the form (for creating a new post):

// When the form is submitted, post it!
actions: {
// createNew begin
createNew() {
  var title = this.controller.get('title');
  var content = this.controller.get('content');

  const data = {
    "posts": [
      {
      "title": title,
      "content": content
      }
    ]
  };
  return this.store.createRecord('posts', data).save().
    then(function(post) {
      console.log(post);
    }, function(error) {
      console.log(error);
    });
} // end of createNew
}

'posts' model:

import DS from 'ember-data';

export default DS.Model.extend({
    posts: DS.hasMany('single'),
});

'single' model: import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr('string'),
  content: DS.attr('string'),
});

And then my serializer to hook the two together...

import DS from 'ember-data';

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    posts: { embedded: 'always' }
  }
});

Currently, this is the error that outputs:

"Assertion Failed: All elements of a hasMany relationship must be instances of DS.Model, you passed [[object Object]]"

In Short: I need to create data models that can represent the following JSON structure:

{

"posts": [

    { "title": "Title", "content": "Content" }

 ]

}

Thanks!




Aucun commentaire:

Enregistrer un commentaire