问题
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