How to use a string as a primary key with Ember Data?

做~自己de王妃 提交于 2019-12-10 10:08:15

问题


I have the following code:

Pult.Zone = DS.Model.extend({
  name: DS.attr('string'),
  authoritative: DS.attr('boolean'),
  user_id: DS.attr('number'),
  rulesets: DS.hasMany('Pult.Ruleset')
});

Pult.RESTAdapter.map('Pult.Zone', {
  primaryKey: 'name',
  rulesets: { key: 'rulesetIds' }
});

However, it doesn't seem like is picking up on the primary key correctly. I have rendered a list of all zones.

Here's a test case:

zones = Pult.store.findAll(Pult.Zone);
zones.get('length'); // Returns 10
zones = Pult.store.findAll(Pult.Zone);
zones.get('length'); // Returns 20

So every time I load zones from the server, it adds them to the local list, since it does not recognize them as already existing. Any way to fix this, or will I have to try to mock up some surrogate keys?


回答1:


After upgrading to Ember Data 1.0.0 Beta 2, I found a solution that works:

App.Zone = DS.Model.extend({
  name: DS.attr('string'),
  user_id: DS.attr('number'),
});

App.ZoneSerializer = DS.RESTSerializer.extend({
  normalize: function(type, hash, property) {
    // Ember Data use the zone name as the ID.
    hash.id = hash.name;

    // Delegate to any type-specific normalizations.
    return this._super(type, hash, property);
  }
});


来源:https://stackoverflow.com/questions/16005198/how-to-use-a-string-as-a-primary-key-with-ember-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!