2016-04-09 7 views
0

Ember 2.4.1を使用しており、自己参照モデルを使用して階層ツリーを構築しようとしています。あなたは、ID 5でカテゴリーを見ることができるよう埋め込みデータにhasManyリレーションを持つEmberデータ

{"categories":[ 
    { 
     "id":4, 
     "name":"Root element w/o children", 
     "type":"Category", 
     "children":[] 
    }, 
    { 
     "id":5, 
     "name":"Root element with a child", 
     "type":"Category", 
     "children":[ 
      { 
       "id":6, 
       "name":"A child", 
       "type":"Category", 
       "children":[] 
      } 
     ] 
    } 
]} 

:ここ

は私のエンバーモデル埋め込まれたデータとルート/categories

// app/models/category.js 
import DS from 'ember-data'; 
export default DS.Model.extend({ 
    name: DS.attr('string'), 
    parent: DS.belongsTo('category', { inverse: 'children' }), 
    children: DS.hasMany('category', { embedded: 'always', async: false, inverse: 'parent' }) 
}); 

サーバの応答(私はエンバー側RESTAdapterを使用する)でありますid 6の子供がいて、それが埋め込まれています。しかし、Emberがページを読み込んでいる間にエラーが発生します:Assertion Failed: You looked up the 'children' relationship on a 'category' with id 5 but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (DS.hasMany({ async: true }))

{categories: [{id:4, …}, {id:5, …}, {id:6, …}]}のようにJSONルートにID 6のカテゴリを含めると、エラーは消えますが、なぜこの場合に埋め込みが必要かわかりません。私はEmberに埋め込みがどのように動作するのか分かりません。

Ember Dataを埋め込みレスポンスで正しく動作させる方法を教えてください。async: trueを使わずに複製しないでください。

UPD @TheCompilerはコメントで私の質問に答えました。 mixinとシリアライザを追加すると、私の問題は解決します:

// app/serializers/category.js 
import DS from 'ember-data'; 
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { 
    attrs: { 
     children: { embedded: 'always' } 
    } 
}); 

答えて

0

レコードを複製する必要はありません。 Rest Adapterは入れ子になったJSONオブジェクトでうまく再生できません。

{"categories":[ 
    { 
     "id":4, 
     "name":"Root element w/o children", 
     "type":"Category", 
     "children":[] 
    }, 
    { 
     "id":5, 
     "name":"Root element with a child", 
     "type":"Category", 
     "children":[6] 
    }, 
    { 
     "id":6, 
     "name":"A child", 
     "type":"Category", 
     "children":[] 
    } 
]} 
+0

この場合、埋め込みは無意味ですか? –

+1

説明した方法でデータを書式設定することをお望みなら、RESTSerializerでEmbeddedRecordsMixinを使用できます。詳細はこちら:http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html – TheCompiler

関連する問題