如何使用hasMany和belongsTo关联创建记录? [EmberJS]

时间:2013-05-03 16:37:38

标签: ember.js ember-data

我正在与Ember一起使用Rails Backend

Ember.VERSION : 1.0.0-rc.3 ember.js:349
Handlebars.VERSION : 1.0.0-rc.3 ember.js:349
jQuery.VERSION : 1.9.1 

我有三个模特

App.SocialNetwork = DS.Model.extend({
  name: DS.attr('string'),
  actors: DS.hasMany('App.Actor'),
  relations: DS.hasMany('App.Relation'),
});

App.Actor = DS.Model.extend({
  name: DS.attr('string'),
  x: DS.attr('number'),
  y: DS.attr('number'),
  social_network: DS.belongsTo('App.SocialNetwork'),
  relations: DS.hasMany('App.Relation'),
  isSelected: function () {
   return false;
  }.property(),
});

App.Relation = DS.Model.extend({
  name: DS.attr('string'),
  actors: DS.hasMany('App.Actor'),
  social_network: DS.belongsTo('App.SocialNetwork'),
});

在我的RelationsController中,我想创建一个新的Relation实例

我试着这样做

App.RelationsController = Ember.ArrayController.extend({
  currentRelation: null,
  add: function () {
    // get the selected actors
    var actors = this.get('socialNetwork.actors').toArray().filter(function (element) {
      return element.get("isSelected") == true;
    });
    // create the new relation with those actors
    var newRelation = App.Relation.createRecord({
      actors: actors,
      name: "New Relation",
    });
    this.set('currentRelation', newRelation);
    this.get('content').pushObject(newRelation);
    this.get('store').commit();
  },
});

但是关系没有被存储,我调试了创建的新记录,它没有任何演员或社交网络关联。

我做错了什么或不做什么?

提前感谢您的帮助

PS:顺便说一句,社交网络和演员正确加载

1 个答案:

答案 0 :(得分:1)

看起来你忘记了belongsTo关系的一面。添加

relation: DS.belongsTo('App.Relation')

到您的App.Actor模型。