Hi, I have a model:
// app/models/expert.js
export default DS.Model.extend({
...
user: DS.belongsTo('user');
...
});
and an API that gives JSON data of the form:
# /experts/07ecb03699efe504
{
"id": "07ecb03699efe504",
...
"user": 54,
...
}
user
is another model that works well and correspond to API endpoints /users/
and /users/<id>/
. So the relationship is just given by the id of the model. This is what I do for all my models and works well in general.
But with this particular model (expert
), the user
object is not loaded when used (for instance in a template) and all expert.user
, expert.get('user')
and expert.get('user.id')
are undefined
(assuming expert
is an instance of the expert
model)… I get no error in the console so everything looks fine, but the data is not loaded and no request goes out to the /users/54
endpoint…
When I inspect the relationship with ember inspector, I have something like user: <(unknown):ember420>
and if I send it to the console I get:
Seems like a bug to me, but not sure…
How could I investigate it further?
So I think user
needs to be userId
Hi! I use the belongsTo
relationships like that in a lot of models, always referring the models by their ids on the API side, and it works well. I’m using a Django back-end and ember-django-adapter on the client side.
My understanding is that ember data has no special naming convention on model fields, except the id
field which must be present. No convention is mentioned in the guides Relationships - Models - Ember Guides (I’m still on Ember 3.4).
If it were working like on other models, I would have access to expert.get('user')
which would resolve to a user instance. Trying to read this would trigger a request to the API to get the user instance. And expert.get('user.id')
would be the users’ id. I think it should be available even before the request has started, but not sure.
But I must admit that Ember Data is still a lot of magic to me… And its code not easy to read…
What is not completely clear to me is whether I can drop the get
or not with v3.4.
Your code and server response looks ok at first glance (though it’s been a while since I’ve used DRF). have you customized the serializer/adapter(s) in any significant way? in terms of debugging you could look at the belongsToReference
for this relationship e.g. expert.belongsTo('user')
(it looks like you were already doing that with the inspector above) and take a look at a few things:
- what does
expert.belongsTo('user').id()
return?
- what are the values on some of the relevant flags (
hasAnyRelationshipData
, hasFailedLoadAttempt
, relationshipIsEmpty
, relationshipIsStale
, etc)
- if these look ok what happens if you do
expert.belongsTo('user').load()
and then also reload()
?
The other alternative for debugging this is stepping through the serializer layer to make sure the record gets the relationship serialized appropriately.
1 Like