【问题标题】:Objects in Ember DataEmber 数据中的对象
【发布时间】:2017-02-23 18:01:18
【问题描述】:

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

我想将“帖子”发布到我的服务器,所以我有一个“帖子”模型,然后是一个“单一”模型。 “帖子”模型代表所有帖子,然后我的“单个”模型代表每个帖子需要什么......我是 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" }

 ]

}

谢谢!

【问题讨论】:

    标签: javascript ember.js ember-data


    【解决方案1】:

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

    “断言失败:hasMany 关系的所有元素都必须是 DS.Model 的实例,您传递了 [[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);
    

    【讨论】:

    • 我相信这是可行的,但我的服务器抛出 400 错误;导致我认为内容的格式不正确.. {"errors":[{"post":["Must be an object"]},{"post.title":["Must be a string"]} ,{"post.content":["必须是字符串"]}]}
    • “引导我思考”并没有给我任何有用的信息来帮助我。您应该检查网络并实际查看正在发送的内容以及错误发生的确切位置(服务器和/或客户端上的代码)。一种想法是您在发送时没有正确序列化内容。检查posts.toJSON() 返回什么。
    猜你喜欢
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多