Optional relationship?

I’m using Ember Data 4.1 and Ember 4.7.

I have tables named person and photo. What I want is for this relationship to be optional. A person may have many photos or none at all. A photo may be owned by a person or have no owner.

I thought I could use hasMany and belongsTo in both model scripts by setting {inverse: null} like:

My person model has this: @hasMany(“photo”, { inverse: null }) photo;

My photo model has this: @belongsTo(“person”, { inverse: null }) person_id;

This works fine until I try to save a photo with the photo.person_id set to null. But while the photo record is saved with photo.person_id = null, Ember Data tries to find a person with an id of 0. That results in this error:

Error: Assertion Failed: You made a ‘findRecord’ request for a ‘person’ with id ‘0’, but the adapter’s response did not have any data.

My API returns false when a single record is not found. Is there a way to do what I’m trying to do with Ember Data?

I think Ember Data works how you expect, relationships are optional. The problem is that it think there’s a record with id 0 and it’s trying to fetch it. This makes it sound like the problem might actually be with serialization or with the API responses. Can you share more about your API responses for the POST requests?

The Request payload, when I set person_id =null, includes person_id: null and my backend also records it as null .

However, what I didn’t notice before is that the response is different and includes: "person_id": 0. I guess that is why Ember Data is trying to locate a person with id=0.

How do I fix this?

Ok that’s kinda what I was guessing. Do you have control over the API code? Sounds like maybe the backend is serializing null => 0 for some reason.

If not you could also handle this in the ember serializer layer by taking a relationship id value of 0 and replacing it with null. Several ways to accomplish that, normalize() is generally a good place to start.

Your guess was dead on – my backend was serializing null values to 0. Once I fixed that, everything works fine. Thanks for your help!

Awesome! Glad you got it working!