javascript - Ember 数据中的对象

标签 javascript ember.js ember-data

这个问题已经被问过几次了,但是这些例子并没有多大帮助。

我想将“帖子”发布到我的服务器,因此我有一个“帖子”模型,然后是一个“单一”模型。 “帖子”模型代表所有帖子,然后我的“单个”模型代表每个帖子需要的内容...我是 Ember.js 的新手,确实可以在这里使用手/方向。

因此,当我提交表单(用于创建新帖子)时:

// 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
}

“帖子”模型:

import DS from 'ember-data';

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

“单一”模型: 从“ember-data”导入 DS;

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

然后我的序列化器将两者连接在一起......

import DS from 'ember-data';

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

目前,这是输出的错误:

“断言失败:hasMany 关系的所有元素都必须是 DS.Model 的实例,您传递了 [[object Object]]”

简而言之:我需要创建可以表示以下 JSON 结构的数据模型:

{

"posts": [

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

 ]

}

谢谢!

最佳答案

该错误实际上准确地说明了问题所在。

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

模型 posts 与模型 single 具有 hasMany 关系。 您的代码所做的是传递一个普通的 JS 对象而不是模型。

const data = {
  "posts": [
    {                    // <-
      "title": title,    // <-
      "content": content // <- this is a POJO
    }                    // <-
  ]
};

实际上解决这个问题的一种方法是分别创建两个对象。

// create 'posts' and 'single' separately
const posts = this.store.createRecord('posts');
const single = this.store.createRecord('single', {
  title,
  content
});
// link them up
posts.get('posts').addObject(single);

关于javascript - Ember 数据中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42422991/

相关文章:

javascript - AngularJS:使用 Controller 和 ng-repeat 在 div 上重新加载数据

ember.js - 如何获取Ember数据模型的商店名称

javascript - Ember linkedin api 身份验证 token 问题

javascript - Ember 幻影模型 : For multiple hasMany and belongsTo

ember.js - 编译 Ember 数据

JavaScript 输入意外结束

php - 使用 PHP 中的 json_encode 时,JQuery $.each 循环会重新排序我的数组

javascript - 访问类变量

ember.js - 如何在 emberjs 的模型 Hook 中返回 dataTable 服务器端响应?

ember.js - Ember 数据和 Northwind OData