Embedded records only on creation (POST request)


#1

Hello everyone! I’m dealing with this problem and I cannot find a nice solution. I’ve a model with a hasMany relationship. When I create them I want to send in the same request the related models that also will be created. But I query them, I need the relationship to be serialized as an array with ids.

Let’s see an example. We have two models like the folllowing

/* models/mouth.js */
export default DS.Model.extend({
    ownerName: DS.attr("string"),
    teeth: DS.hasMany("tooth", {async: true})
});

/* models/tooth.js */
export default DS.Model.extend({
    position: DS.attr("number"),
    mouth: DS.belongsTo("mouth", {async: true})
});

When I create mouth records I want them to be serialized like this:

{
    ownerName: "James",
    tooth: [
        {position: 24},
        {position: 25},
        {position: 26}
    ]
}

But when I query them I don’t want the embedded records. Instated, an array with the tooth’s ids.

{
    ownerName: "James",
    tooth: [1, 2, 3]
}

#2

You will have to extend a serializer and modify methods like normalizeQueryResponse and serialize. If you could provide what your JSON response looks like that could help.


#3

Hi @injaon! As David rightly pointed out, there are two parts to consider:

  1. Posting a mouth. If you want to post tooth entities alongside mouth you probably will have to use something like EmbeddedRecordsMixin and/or extend serialize in MouthSerializer.

  2. Retrieving a mouth: It totally depends on what your API returns. You can transform the server response overriding the MouthSerializer's normalizeFindRecordResponse to return what you need.


#4

thanks guys! @emberigniter @skaterdav85 This is JSON response look like.

For creating mounth and theets, this my POSt response

{
    id: 12,
    ownerName: "James",
    tooth: [
        {id: 1, position: 24},
        {id: 2, position: 25},
        {id: 3, position: 26}
    ]
}

The GET reponse for queing the mouth look like this

{
    id: 12,
    ownerName: "James",
    tooth: [1,2,3]

My current and very ugly solution is to have two models:

createMouth: only used to create Mouth and its serializers extends EmbeddedRecordsMixin mouth: used for the other operations.

So, are you suggesting I need to modify the serializer?


#5

I’d probably have 2 models here: mouth and tooth. A mouth hasMany() tooth. Use JSONSerializer since your GET response looks like it fits that format already. Then, create a mouth serializer, and override the serialize method to adjust the POST format.