Marten
Marten

Reputation: 1384

Save nested models using Ember Data

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.

Upvotes: 0

Views: 546

Answers (2)

acorncom
acorncom

Reputation: 5955

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!

Upvotes: 1

myartsev
myartsev

Reputation: 1232

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.

Upvotes: 0

Related Questions