我正在为Ember数据滚动一个localStorage adaper,当我运行find函数时,即:
App.store.find(App.Person, 0 );
我收到此错误:
Uncaught Error: assertion failed: A data hash was loaded for a model of type App.Person but no primary key 'undefined' was provided.
在更一般的层面上,我对'持久层'(在本例中为localStorage)和Ember Store之间的关系感到有点困惑。将东西装到商店意味着什么?这是否意味着DS.Person模型的实例是使用数据创建的?
另外,如果你注意到我在createRecord方法中注释了一行“App.store.didCreateRecord(model,data)”,因为它也没有用。如果我在记录加载到localStorage后没有调用store.didCreateRecord会发生什么。
细节:
DS.LocalStorageAdapter = DS.Adapter.extend({
get: Ember.get,
set: Ember.set,
createRecord: function( store, modelType, model ){
var records, index, data;
// get existing records of this model
records = this.localStorage.get( modelType );
index = records.length;
data = this.get( model, 'data' );
// set storageID of data
data.set( 'storageID', index );
// add data to existing records
records[index] = data;
// encode records
records = JSON.stringify( records );
// store records in localStorage
this.localStorage.set( modelType, records );
// App.store.didCreateRecord( model, data );
},
find: function( store, modelType, id ) {
var records, model;
records = this.localStorage.get( modelType );
model = records[id];
App.store.load( modelType, model );
},
localStorage: {
set: function( modelType, value ){
localStorage.setItem( modelType, value);
},
get: function( modelType ){
var record = localStorage.getItem(modelType);
record = JSON.parse(record) || [];
return record;
}
}
});
//application model
App.Person = DS.Model.extend({
name: DS.attr('string', {key: 'css_name'}),
storageID: DS.attr('number', {defaultValue: 0, key: 'storageID'}),
});
//create a couple of records
App.store.createRecord(App.Person, { ... } );
App.store.createRecord(App.Person, { ... } );
//try and find one record
App.store.find(App.Person, 0);
error thrown:
Uncaught Error: assertion failed: A data hash was loaded for a model of type App.Person but no primary key 'undefined' was provided. ember-latest.js:51
Ember.assert ember-latest.js:51
(anonymous function) ember-latest.js:131
DS.Store.Ember.Object.extend.load ember-data.js:1530
DS.LocalStorageAdapter.DS.Adapter.extend.find bookApp_1.js:111
DS.Store.Ember.Object.extend.findByClientId ember-data.js:1174
DS.Store.Ember.Object.extend.find ember-data.js:1140
findRecord webApplication.js:210
onclick
另请注意,这与之前发布的另一个问题类似: Ember Data: A data hash was loaded ... but no primary key 'undefined' was provided
虽然答案似乎并没有真正解释发生了什么。
答案 0 :(得分:0)
可以举例说明加载Ember 1.0 pre2的夹具数据
App.store = DS.Store.create({
revision: 11,
adapter: 'DS.FixtureAdapter'
});
App.User = DS.Model.extend({
email: DS.attr('string'),
password: DS.attr('string')
});
App.User.FIXTURES = [
{
"id": "1",
"email": "test@mail.com",
"password": "password"
}
];
App.User.find(1).get('email')
适合我。