【问题标题】:How to create a record (in ember.js) with belongsTo relationship and persist it in django via tastypie?如何创建具有belongsTo关系的记录(在ember.js中)并通过tastepie将其保存在django中?
【发布时间】:2014-09-19 15:53:03
【问题描述】:

所以我正在做一个聊天应用程序(前端在 ember.js 中,后端在 django 中)当然必须发送消息。

我在 ember.js 中的消息模型如下所示:

Messages.Message = DS.Model.extend({
    body: attr('string'),
    user: DS.belongsTo('user'),
    time: attr('date'),
    recipient: DS.belongsTo('recipient'),
});

我尝试使用此示例中的代码创建和保留新消息:http://emberjs.com/guides/models/creating-and-deleting-records/

所以我在控制器中的 saveMessage 操作如下所示:

var store = this.store;

var message = store.createRecord('message', {
    body: 'Lorem ipsum'
});

store.find('recipient', 2).then(function(recipient) {
    message.set('recipient', recipient);
});

message.save();

但是生成的 JSON 的属性 'recipient' 为空,因此服务器返回错误 500,因为该字段不能为空白。

JSON 应该是这样的:

{'body': 'loremipsum', 'recipient': {'username','some name'}, 'time': null, 'user': null}

你知道怎么做吗?

【问题讨论】:

    标签: jquery json django ember.js tastypie


    【解决方案1】:

    find 是异步的,并返回一个承诺。这意味着传递给then 的匿名函数可能会在您调用save 之后执行。将 save 移到 then 中,以便在保存之前附加收件人。

    var store = this.store;
    
    var message = store.createRecord('message', {
        body: 'Lorem ipsum'
    });
    
    store.find('recipient', 2).then(function(recipient) {
        message.set('recipient', recipient);
        message.save();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-27
      • 1970-01-01
      • 2014-02-01
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      相关资源
      最近更新 更多