ember.js,如何在新创建的记录中设置关系

时间:2014-08-11 10:29:20

标签: ember.js

我想设置新创建的两条记录之间的关系:我创建country,创建city,然后设置country hasMany city,反过来city belongsTo country。来自ember "Models guide"

  

您不能将承诺指定为关系[...]但是,您可以在履行承诺后轻松设置关系:

var store = this.store;

var post = store.createRecord('post', {
  title: 'Rails is Omakase',
  body: 'Lorem ipsum'
});

store.find('user', 1).then(function(user) {
  post.set('author', user);
});

上面的示例并不完全适合我的情况,因为我不知道id记录的user,该记录在片段中被假定为{{1} }。我的例子更像是

1

然后,在操作记录时,我想一次性创建和链接:

App.Country = DS.Model.extend({
  name: DS.attr('string'),
  cities: DS.hasMany('city', {async: true})
});

App.City = DS.Model.extend({
  name: DS.attr('string'),
  country: DS.belongsTo('country', {async: true})
});

问题是:在我上面的代码段中放入var store = this.store; var country = store.createRecord('country', { name: 'France' }); var city = store.createRecord('city', { name: 'Paris' }); // How to get the 'foo' created just above out of the store? What id? store.find('city', ??).then(function(city) { country.set('cities', [city]); }); // Same story, what's the id of the country I just created? store.find('country', ??).then(function(country) { city.set('country', country); }); 的内容。

2 个答案:

答案 0 :(得分:1)

我实施它的方式 -

var store = this.store;


var onCountrySuccess = function(resolvedCountry){
resolvedCountry.get('id');
};

var onCountryFailure = function() {} ;

var onSuccessfulCityCreate = function(resolvedCity){
   store.createRecord('country', {
    name: 'France',
    cities : [resolvedCity]
 }.save().then(onCountrySuccess, onCountryFailure):

var onCityFailure = function(){ alert("Failed") });

var city = store.createRecord('city', {
    title: 'Paris'
}).save().then(onSuccessfulCityCreate, onCityFailure);

如果你有一套城市

var resolve = function(resolvedRecords) {
 store.createRecord('country', {
    name: 'France',
    cities : resolvedRecords
 }.save();
}:
var reject = function(){}; 

var citiesToSave = someCityContainingArray.map(function(city){
 return city.save();
});

Ember.RSVP.all(citiesToSave).then(resolve, reject);

答案 1 :(得分:0)

据我所知,Ember Data无法创建独特的ID。这是您需要在API端点上执行的操作,因此可以链接一些请求,直到您完成所有关系并正确保存为止。

例如:

var country = store.createRecord('country', {
    name: 'France'
});

var city = store.createRecord('city', {
    name: 'Paris'
});

country.save().then(function (country) {

  city.set('country', country);
  return city.save();

}).then(function (city) {

  country.get('cities').addObject(city);
  return country.save();

}).then(function () {

  alert('all done.');

});