0
votes

I've a model with store attribute in it. Unfortunately store is a reserved word in ember-data so I had to change its name to authStore. I can't change backend API to use new attribute name, so I've created a new serializer just for this model.

Model is:

App.Auth = DS.Model.extend({
  status: DS.attr("string"),
  authStore: DS.belongsTo("store"),
});

If I use following serializer, json sent to server contains the right store key

App.AuthSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    authStore: 'store',
  }
});

But I also need to specify embedded: 'always' for authStore attribute and so I've update the serializer to

App.AuthSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    authStore: {key: 'store', embedded: 'always'}
  }
});

This way key attribute is ignored and even if authStore is embedded when json is sent to server, key attribute is ignored and it has key authStore instead of store. How can I make both key and embedded attributes work togheter?

I'm using ember-cli 0.2.7 and ember-data 1.0.0-beta.18

2

2 Answers

2
votes

Not sure why key is being overridden, but in the meantime, I think in your serializer you can do something like this:

App.AuthSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    authStore: {embedded: 'always'}
  },

  normalize: function(typeClass, hash) {
    hash.authStore = hash.store;
    delete hash.store;
    return this._super(typeClass, hash)
  },

  serialize: function(snapshot, options) {
    var json = this._super(snapshot, options);
    json.store = json.authStore;
    delete json.authStore;
    return json;
  }
});

Doesn't seem to be any easy to find docs on something I'm sure other people have run in to.

1
votes

embedded: 'always' is the same as writing serialize: 'records', deserialize: 'records', where records can also be ids, false, or their singular if relationship is a belongsTo.

As such, try:

App.AuthSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    authStore: {key: 'store', serialize: 'records', deserialize: 'records'}
  }
});

I have managed to make a model called store by wrapping it in quotes. Here is a copy from the Operators Serializer, where Operators has a hasMany relationship with "store":

attrs: {
    "stores" : { deserialize: 'records', serialize: 'ids' }
}