Save nested models using Ember Data

喜夏-厌秋 提交于 2019-12-25 09:29:58

问题


I have two models in Ember:

Collection

export default DS.Model.extend({
    name: DS.attr(),
    description: DS.attr(),
    items: DS.hasMany('collection-item')

});

Collection Item

export default DS.Model.extend({
    date: DS.attr(),
    volume: DS.attr(),
    sequenceNumber: DS.attr()
});

I want to save the collection items inside the 'items' attribute of the collection, like MongoDB:

[{
    "name": "First Collection",
    "description": "This is my first collection",
    "items": [
        {
            "date": "2017-07-26",
            "volume": "1",
            "sequenceNumber": "1"
        },
        {
            "date": "2017-07-27",
            "volume": "1",
            "sequenceNumber": "2"
        }
    ]
},
{
    "name": "Second Collection",
    "description": "This is my second collection",
    "items": [
        {
            "date": "2017-07-26",
            "volume": "1",
            "sequenceNumber": "1"
        },
        {
            "date": "2017-07-27",
            "volume": "1",
            "sequenceNumber": "2"
        }
    ]
}]

I have read something about serializers, but I don't get the point ;) Can someone give me a hint?

BTW, I'm using Firebase (emberfire) for now, but I'm going to build my own API in future.


回答1:


What you're describing is known as an embedded record in Ember. On the serializers page, beneath the discussion of the JSONAPISerializer is a discussion of the embedded record mixin: https://guides.emberjs.com/v2.14.0/models/customizing-serializers/

You can use a RESTSerializer with an embedded mixin to achieve what you're after.

That said, unless your backend needs are fairly simple, I'd suggest beginning to build a backend (and using JSON-API for it) before you get too far. JSON-API is a spec based off of pain points the entire Ember community has felt over the years. If you build a simpler backend right now, you may find yourself hitting headaches in the future that JSON-API is specifically designed to address.

Good luck!




回答2:


If you are using the defaults from Ember Data, you need to have a JSON API compatible backend service where to retrieve/send data from. You can take a look at the projects implementing JSON API standards if you don't have a backend yet.

After you have a working API, the rest is fairly straightforward and well documented.



来源:https://stackoverflow.com/questions/45353769/save-nested-models-using-ember-data

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