2013-12-09 6 views
15

実際のレコードをフェッチせずにbelongsTo IDを取得しようとしています。私のJSON APIは、belongsTo関係のIDを返します。レコードを取得せずにbelongsTo IDを取得

私はこれが私のルートで、次のモデル

App.Recipe = DS.Model.extend(
    title: DS.attr() 
    ingredients: DS.hasMany('ingredient', async: true) 
) 

App.Ingredient = DS.Model.extend(
    recipe: DS.belongsTo('recipe') 
    product: DS.belongsTo('product', async: true) 
) 

App.Product = DS.Model.extend(
    title: DS.attr() 
) 

を持っている:

App.RecipeIndexRoute = Ember.Route.extend(
    model: (args) -> 
    @store.find('recipe', args.recipe_id) 
) 

これは私のコントローラである:

私は見つけようとしていますこのコントローラ内の製品ID。

App.RecipeIndexController = Ember.ObjectController.extend(
    hasRecipeInCart: null 

    actions: 
    toggleCart: -> 
     @content.get('ingredients').then((ingredients) => 
     # how do I get product id here, without lookup up the product relation? 
     # this 'get' makes Ember call: /api/v1/products/1 
     # I simply want the product ID (in this case 1), without having to call the server again. 
     ingredient.get('product').then((product) => 
      product.id # => 1 
     ) 

私のJSONは、次のようになります。

HTTP GET:/ API/V1 /レシピ/ 1

{ 
    "recipe": { 
    "id":1, 
    "title":"Recipe 1", 
    "ingredients":[2,1] 
    } 
} 

HTTP GET:/ API/V1 /食材IDS []? = 2つの& IDS [] = 1

{ 
    "ingredients": [ 
    { 
     "id":2, 
     "recipe":1, 
     "product":1 
    }, 
    { 
     "id":1, 
     "recipe":1, 
     "product":2 
    } 
    ] 
} 

答えて

6

作業のトンは、再をやり直すに起こっていますlationshipsは、あなたがデータ属性model.get('data.product.id')

例からの根本的な性質からそれを引くことができます:ED 2.Xについてhttp://emberjs.jsbin.com/OxIDiVU/16/edit

+0

を参照してください。私はこのコードを使用しました:@ content.get( 'ingredients')。then((ingredients)=> ingredients.forEach(成分、インデックス、列挙可能)=> productId = ingredients.toJSON()。サーバへの呼び出し – Martin

+1

これはEDの醜い実装です。私はPRを行う必要があるかもしれないし、なぜjsonのためにモデルをフェッチしているのかを調べるかもしれません。 – Kingpin2k

+0

ingredient.get( 'data ').product.id または ingredients._data.product.id – Martin

5

、関係が再加工されている基礎となるデータuntil the ds-references feature landedを取得するために破壊しました。

ED 2.4+でこれを行うには、新しいbelongsToメソッドを使用して基礎となるデータを処理する必要があります。

はbelongsToのrefのためのIDを取得するには:

var id = this.get('model').belongsTo('myBelongsToKey').value(); 
+1

ds-referencesは着陸しました:) http://emberjs.com/blog/2016/05/03/ember-data-2-5-released.html#toc_code-ds-references-code – ianpetzer

関連する問題