1

我正在使用模型“鸡尾酒”、“会员”和“成分”创建一个鸡尾酒应用程序。鸡尾酒和配料模型非常容易解释,会员模型适用于将鸡尾酒与配料联系起来的对象。

App.Cocktail = DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
  created_by: DS.attr('number'),
  start_date: DS.attr('string'),
  end_date: DS.attr('string'),

  // link cocktail to memberships
  membership: DS.hasMany('membership',{ async: true })
});

App.Membership = DS.Model.extend({
  amount: DS.attr('string'),

  // link membership to ingredient and cocktail
  ingredient: DS.belongsTo('ingredient'),
  cocktail: DS.belongsTo('cocktail')
});

App.Ingredient = DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
  start_date: DS.attr('string'),
  end_date: DS.attr('string')
});

我遇到的问题是,当我使用 ember-data 创建鸡尾酒,然后它的成员资格成分和 REST 调用的鸡尾酒 ID 是字符串而不是整数时,请求正文如下所示:

{membership:{amount:"2 litres",ingredient:"12",cocktail:"116"}}

当我想要什么时:

{membership:{amount:"2 litres",ingredient:12,cocktail:116}}

这是我执行保存的代码,我对 Promise 的想法很陌生,所以不确定这是否以最可取的方式构建。

... code
  actions: {
    // fired when user presses save
    submit: function() {
      // some validation

      var cocktailPromise = this._saveCocktail();
      this._saveIngredientMemberships(cocktailPromise);
    }
  }
... more code
  _saveCocktail: function() {
    console.log('saving cocktail');

    var cocktail = this.store.createRecord('cocktail', {
      name: this.get('cocktailName'),
      description: this.get('cocktailDescription'),
      start_date: "now"
    });

    return cocktail.save();
  },

  _saveIngredientMemberships: function(cocktailPromise) {
    console.log('saving cocktail ingredients');

    // get the ingredients and amounts (memberships) the 
    // user entered and the store and set them as var here 
    // so they stay in scope.
    var memberships = this.get('memberships');
    var store = this.store;

    // once cocktail is created
    cocktailPromise.then(function(cocktail) {
      console.log('cocktail ready, saving ingredients');

      var membershipRecords = [];

      for( var i = 0 ; i < memberships.length ; i++ ) {
        membershipRecords[i] = store.createRecord('membership', {
          cocktail: cocktail,
          ingredient: memberships[i].get('ingredient'),
          amount: memberships[i].get('amount')
        });

        membershipRecords[i].save();
      }

    }, function() {
      console.log('something went wrong saving the cocktail!');
    })
  },
4

1 回答 1

1

默认情况下,Ember 将所有 ID 视为字符串(它将数字强制转换为字符串)。您要做的是覆盖RESTSerializer. 您可以在此处找到所有可能的覆盖方法。我建议您也阅读适配器的源代码。这真的很有帮助。自从我使用 Ember-Data 以来已经有一段时间了,但我相信您要查看的方法是serialize。我会做这样的事情:

App.ApplicationAdapter = DS.RESTAdapter.extend({
    serialize: function(record, options) {
        var json = this._super(record, options);
        json.ingredient = parseInt(json.ingredient);
        json.cocktail = parseInt(json.cocktail);

        ...

        return json;
    }
});

您显然可以使其对不同的模型更有效,但您明白了。您可能还可以覆盖更具体的方法,这也是我建议阅读源代码的原因。

于 2014-03-30T18:54:46.860 回答