2013-12-09 11 views
15

Próbuję pobrać identyfikator belongsTo ID bez pobierania rzeczywistego rekordu. Moja funkcja JSON API zwraca identyfikator dla relacji belongsTo.Pobierz identyfikator tożsamości bez pobierania rekordu

Mam następujące modele

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() 
) 

To moja droga:

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

To jest mój kontroler:

Próbuję odnaleźć identyfikator produktu w tym kontrolerze.

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 
     ) 

Moje JSON wygląda następująco:

HTTP GET:/api/v1/recepty/1

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

HTTP GET:/api/v1/Składniki identyfikatory [] = 2 & identyfikatory: [] = 1

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

Odpowiedz

6

ton pracuje się do ponownego wykonania ponownego lationships, można wyciągnąć go z właściwościami bazowych z atrybutów dane model.get('data.product.id')

Przykład: http://emberjs.jsbin.com/OxIDiVU/16/edit

+0

który wyzwala również połączenia z serwerem:/api/v1/products/1, z jakiegoś powodu. Użyłem tego kodu: @ content.get ("składniki"). Then ((składniki) => ingredients.forEach ((składnik, indeks, przeliczalny) => productId = ingredient.toJSON(). Product # this line triggers Wezwanie do serwera – Martin

+1

To brzydka implementacja w ED, może będę musiał zrobić PR lub dowiedzieć się, dlaczego pobiera on modele dla json. – Kingpin2k

+0

Możliwe jest uzyskanie identyfikatora produktu w ten sposób: ingredient.get ("dane ") .product.id lub ingredient._data.product.id – Martin

5

Ed 2.x, relacje zostały przerobione i zostały podzielone na uzyskanie danych źródłowych until the ds-references feature landed.

Aby to zrobić w wersji ED 2.4+, należy użyć nowej metody belongsTo do pracy z danymi podstawowymi.

Aby uzyskać identyfikator dla ref belongsTo:

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

ds-references wylądował :) http://emberjs.com/blog/2016/05/03/ember-data-2-5-released.html#toc_code-ds-referencje-code – ianpetzer

Powiązane problemy