【问题标题】:record was saved to the server, but the response does not have an id and your record does not either记录已保存到服务器,但响应没有 id,您的记录也没有
【发布时间】:2018-09-19 12:21:53
【问题描述】:

从昨天开始我就遇到了这个错误,错误:断言失败:'todo' 已保存到服务器,但响应没有 id,您的记录也没有。

我知道它应该来自 app/serializers/todo.js 或我的 app/routes/application.js 但是在查看了几个论坛之后,我不得不向专家 emberJs 开发人员提问,因为我是新手:笑脸:

这里是my app/serializers/todo.js

import DS from 'ember-data';

export default DS.JSONSerializer.extend({
  serialize: function(record, options) {
    var json = this._super.apply(this, arguments); // Get default serialization

    json.id = record.id;  // tack on the id

    return json;
  }
});

还有我的app/routes/application.js

import Route from '@ember/routing/route';

export default Route.extend({
  model(){
    return this.store.findAll('todo');
  },
    actions: {
      createtodo: function() {

        var titleInput = this.get("newTitle")
        var todo = this.store.createRecord('todo', {
          title: titleInput,
          isCompleted: false
        }); 

        this.set('newTitle', '');
        todo.save();
      }
    }
});

createtodo动作的触发方式app/templates/application.hbs

{{input type="text" id="new-todo" value=newTitle}}
<button {{action "createtodo"}}>Save</button>

所以我的对象已创建但未保存。当我查看我的 ember Inspector 时,我看到我创建的每个对象都有一个 ID,但标题字段为 null 或“”。

这是一个以 Rails-API 为背面,Ember 为正面的 todoApp。

有人知道这里有什么问题吗?

【问题讨论】:

    标签: ember.js rails-api


    【解决方案1】:

    您的序列化程序是问题所在。如果您使用的是标准的 api 设置,则根本不需要序列化程序。我会先删除那个。

    可能发生的情况是您的 API 未设置为接收 JSON-API 文档,其结构如下:

    {
      id: <id>,
      type: <type>,
      attributes: {
        name: <string>, 
        created: <date>,
        complete: <boolean>
       }
     }
    

    所以你应该在后端安装一个 json-api gem 或者切换适配器以使用 DS.RestSerializer,它具有完全扁平的数据结构。

    【讨论】:

    • 我和 Enner31 有完全相同的问题,我们所有的序列化器都是 JSONAPISerializers,通常工作正常。只是这个模型(在我们的例子中是“约会”)引发了错误。删除序列化程序或将其更改为 RestSerializer 没有帮助。现在我不知道在哪里继续搜索错误。我们的后端人员说请求和响应看起来都很好,应该可以工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    相关资源
    最近更新 更多