簡體   English   中英

Ember Data屬於從createRecord()save()序列化中省略的異步關系

[英]Ember Data belongsTo async relationship omitted from createRecord() save() serialization

編輯2014年11月16日:版本信息

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

問題是,當模型關系被定義為異步時,類型Id和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()期間不會將belongsTo關系添加到文件JSON。 只序列化基本屬性:

{"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

我有一個工作解決方案(黑客?),我根據兩個相關主題中的信息找到了:

1) async屬性應該如何序列化?

2) async屬於支持相關的模型分配嗎?

基本上,我所要做的就是將Ember.RSVP.all()移到屬性上的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()屬於屬性的屬性。 我不知道這是不是一個bug。 也許對emberjs有更多了解的人可以幫助闡明這一點。

請參閱問題以獲取更多詳細信息,但是在保存具有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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM