3

编辑 11/16/14:版本信息

DEBUG: Ember      : 1.7.0 ember-1.7.0.js:14463
DEBUG: Ember Data : 1.0.0-beta.10+canary.30d6bf849b ember-1.7.0.js:14463
DEBUG: Handlebars : 1.1.2 ember-1.7.0.js:14463
DEBUG: jQuery     : 1.10.2 

我正在努力做一些我认为使用 ember 和 ember-data 应该相当简单的事情,但到目前为止我还没有运气。

本质上,我想使用服务器数据来填充<select>下拉菜单。提交表单时,应根据用户选择的数据创建模型。然后将模型与 ember 数据一起保存并以以下格式转发到服务器:

{ 
    "File": { 
        "fileName":"the_name.txt",
        "filePath":"/the/path",
        "typeId": 13,
        "versionId": 2
    }
}

问题是,当模型关系被定义为异步时,typeId 和 versionId 被遗漏了,如下所示:

App.File =  DS.Model.extend({
    type: DS.belongsTo('type', {async: true}),
    version: DS.belongsTo('version', {async: true}),
    fileName: DS.attr('string'),
    filePath: DS.attr('string')
});

让我感到困惑的部分,也可能是我的错误所在,是控制器:

App.FilesNewController = Ember.ObjectController.extend({
    needs: ['files'],
    uploadError: false,

    // These properties will be given by the binding in the view to the 
    //<select> inputs.  
    selectedType: null,
    selectedVersion: null,

    files: Ember.computed.alias('controllers.files'),

    actions: {
        createFile: function() {
            this.createFileHelper();
        }
    },

    createFileHelper: function() {
        var selectedType = this.get('selectedType');
        var selectedVersion = this.get('selectedVersion');

        var file = this.store.createRecord('file', {
                fileName: 'the_name.txt',
                filePath: '/the/path'
        });

        var gotDependencies = function(values) {

            //////////////////////////////////////
            // This only works when async: false
            file.set('type', values[0])
                .set('version', values[1]);
            //////////////////////////////////////

            var onSuccess = function() {
                this.transitionToRoute('files');
            }.bind(this);

            var onFail = function() {
                this.set('uploadError', true);
            }.bind(this);

            file.save().then(onSuccess, onFail);
        }.bind(this);

        Ember.RSVP.all([
            selectedType,
            selectedVersion
        ]).then(gotDependencies);
    }
});

当 async 设置为 false 时,ember 会createRecord().save()正确处理 POST 请求。

当 async 为 true 时,ember 可以完美地处理多个请求的 GET 请求,但不会在createRecord().save(). 只有基本属性被序列化:

{"File":{"fileName":"the_name.txt","filePath":"/the/path"}}

我意识到以前有人问过这个问题,但到目前为止我还没有找到满意的答案,也没有找到任何适合我需要的东西。那么,如何让 belongsTo 关系正确序列化呢?

为了确保一切都在这里,我将添加到目前为止的自定义序列化:

App.ApplicationSerializer = DS.RESTSerializer.extend({
    serializeIntoHash: function(data, type, record, options) {
        var root = Ember.String.capitalize(type.typeKey);
        data[root] = this.serialize(record, options);
    },
    keyForRelationship: function(key, type){
        if (type === 'belongsTo') {
            key += "Id";
        }
        if (type === 'hasMany') {
            key += "Ids";
        }
        return key;
    }
});

App.FileSerializer = App.ApplicationSerializer.extend(DS.EmbeddedRecordsMixin, {
    attrs: {
        type: { serialize: 'id' },
        version: { serialize: 'id' }
    }
});

和一个选择:

{{ view Ember.Select
    contentBinding="controller.files.versions"
    optionValuePath="content"
    optionLabelPath="content.versionStr"
    valueBinding="controller.selectedVersion"
    id="selectVersion"
    classNames="form-control"
    prompt="-- Select Version --"}}

如有必要,我将附加其他路由和控制器(FilesRoute、FilesController、VersionsRoute、TypesRoute)

编辑11/16/14

我根据两个相关线程中的信息找到了一个可行的解决方案(hack?):

1) async belongsTo 关系应该如何序列化?

2) async belongsTo 是否支持相关模型赋值?

本质上,我所要做的就是将属性移到Ember.RSVP.all()a 之后:get()

createFileHelper: function() {
    var selectedType = this.get('selectedType');
    var selectedVersion = this.get('selectedVersion');

    var file = this.store.createRecord('file', {
            fileName: 'the_name.txt',
            filePath: '/the/path',
            type: null,
            version: null
    });


    file.set('type', values[0])
        .set('version', values[1]);

    Ember.RSVP.all([
        file.get('type'),
        file.get('version')
    ]).then(function(values) {

        var onSuccess = function() {
            this.transitionToRoute('files');
        }.bind(this);

        var onFail = function() {
            alert("failure");
            this.set('uploadError', true);
        }.bind(this);

        file.save().then(onSuccess, onFail);
    }.bind(this));
}

因此get(),在保存模型之前,我需要属于属于关系的属性。我不知道这是否是一个错误。也许对 emberjs 有更多了解的人可以帮助阐明这一点。

4

1 回答 1

1

有关更多详细信息,请参阅问题,但我在保存具有 belongsTo 关系的模型时为我工作的通用答案(并且您特别需要序列化该关系)是调用.get()属性,然后将save()它们放入then().

归结为:

var file = this.store.createRecord('file', {
        fileName: 'the_name.txt',
        filePath: '/the/path',
        type: null,
        version: null
});

// belongsTo set() here
file.set('type', selectedType)
    .set('version', selectedVersion);

Ember.RSVP.all([
    file.get('type'),
    file.get('version')
]).then(function(values) {

    var onSuccess = function() {
        this.transitionToRoute('files');
    }.bind(this);

    var onFail = function() {
        alert("failure");
        this.set('uploadError', true);
    }.bind(this);

    // Save inside then() after I call get() on promises
    file.save().then(onSuccess, onFail);

}.bind(this));
于 2014-11-17T03:38:02.663 回答