我有两个模型,User
和Project
:
App.Project = DS.Model.extend({
name: DS.attr('string'),
url: DS.attr('string'),
user: DS.belongsTo('user')
});
App.User = DS.Model.extend({
name: DS.attr('string'),
projects: DS.hasMany('project')
});
我正在使用Ember Data的本地存储来存储用户和项目。我在IndexController
:
'createUser' : function(){
var name = this.get('newUser');
if(!name){
return;
}
var that = this;
Ember.$.getJSON('<apiUrl>).then(function(data){
var user = that.store.createRecord('user', data);
user.save();
that.set('newUser', '');
Ember.$.getJSON(<apiUrl>/projects').then(function(data){
var length = data.length;
for(var i = 0; i < length; i++){
data[i].id = data[i].name;
data[i].user_id = data.id;
var project = that.store.createRecord('project', data[i]);
project.save();
user.get('projects').addObject(project);
}
user.save();
});
});
},
}
当我转到用户的URL时,项目会正确显示。但是,当我重新加载页面时,项目会消失,不再显示。我对项目的看法是这样的(在用户模板中):
{{#each projects}}
<div class="row">
<a {{bind-attr href="url"}}>{{name}}</a>
</div>
{{else}}
<p>No projects loaded</p>
{{/each}}
我做错了什么导致项目无法重新加载?
答案 0 :(得分:0)
我找到了这个here的答案。为了实现这一点,我需要重新打开JSONSerializer
:
DS.JSONSerializer.reopen({
serializeHasMany : function(record, json, relationship) {
var key = relationship.key;
var relationshipType = DS.RelationshipChange.determineRelationshipType(
record.constructor, relationship);
if (relationshipType === 'manyToNone'
|| relationshipType === 'manyToMany'
|| relationshipType === 'manyToOne') {
json[key] = Ember.get(record, key).mapBy('id');
}
}
});