Ember data: save loses belongsTo relationship

拜拜、爱过 提交于 2019-12-20 05:59:11

问题


I have the following problem:

A form with a select field for selecting the category of a post. Let's say the post has category 100. In Ember inspector, this is shown as follows:

category: <App.Category:ember708:100>

When I save the post (via Ember Data 1.0.0 beta 2), the category suddenly changes to:

category: 100

And the value is no longer selected in the select list. It is cleared.

Code to save:

    post.save().then(
            function () {
              alert("Save OK");
            }
    )

Any idea in which direction I need to search ... If I transition to another page and then go back to the edit screen, the values are all correct. The data is thus still correct in the model ...


回答1:


Get the latest canary build, this will fix the belongsTo issue, but for hasMany I tried modifying the code of ember-data, and it worked so far,

Changed the line no 167 to

if (relationshipType === 'manyToNone' 
 || relationshipType === 'manyToMany' 
 || relationshipType === 'manyToOne') 

Update

Better solution is override serializeHasMany method in your serializer.

Thanks to @wycats (as per discussion on github #1273)

Something like

Deific.AppacitiveRESTSerializer = DS.RESTSerializer.extend({
    //primary key is '__id' in appacitive, overriding default behaviour
    primaryKey: '__id',

    serializeHasMany: function(record, json, relationship) {
        var key = relationship.key;

        var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);

        if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany' || relationshipType === 'manyToOne') {
            json[key] = record.get(key).mapBy('id');
        // TODO support for polymorphic manyToNone and manyToMany relationships
        }
    }
});

Deific.Store = DS.Store.extend({
    revision: 12,
    adapter: DS.RESTAdapter.extend({
        namespace: 'service',
        defaultSerializer: 'Deific/appacitiveREST'
    }),
});

For time being this can be used. Hope this helps.




回答2:


Looks like a bug in Ember Data: https://github.com/emberjs/data/issues/1228




回答3:


Looks like this should be fixed now. https://github.com/emberjs/data/pull/1257



来源:https://stackoverflow.com/questions/18703867/ember-data-save-loses-belongsto-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!