Reputation: 3726
I have an EmberJS model, which is initialized from a JSON object. This JSON object used to contain an id
variable, but now its name is changed. Is there a way to tell the model what to use as id
from the JSON? There are functions which use the model's id
variable, so the best way would be to set id
to be a reference of one of the model's variable.
Upvotes: 1
Views: 764
Reputation: 6116
You can create a serializer (ember generate serializer [name]
) where the name matches your model, and set the primaryKey
that should be used instead of the default id
.
If your backend uses a key other than id you can use the serializer's primaryKey property to correctly transform the id property to id when serializing and deserializing data.
// app/serializers/modelName.js
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
primaryKey: '_id'
});
https://guides.emberjs.com/release/models/customizing-serializers/#toc_ids
Alternatively, you can use the serializer to copy a value TO the id
property via the normalizeResponse
method if you prefer to maintain the primaryKey as id
:
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
normalizeResponse(store, primaryModelClass, payload, id, requestType) {
payload.data.id = payload.data.newModelId;
delete payload.data.newModelId;
return this._super(...arguments);
}
});
Upvotes: 2