Question

I try to model an ajax call via mockjax for ember data.

my models:

App.Service = DS.Model.extend({
  name: DS.attr('string'),
  service_prices: DS.hasMany('servicePrice')
});

App.ServicePrice = DS.Model.extend({
  unit_price: DS.attr('number'),
  qty_unit: DS.belongsTo('qtyUnit'),
  service: DS.belongsTo('service')
});


App.QtyUnit = DS.Model.extend(Ember.Validations.Mixin, {
  name: DS.attr('string'),

});

App.Order = DS.Model.extend({
  service: DS.belongsTo('service'),
  qty_unit:DS.belongsTo('qtyUnit'),
});

I try to load an order record via mockjax. (Push the button.) According to the console after the call

MOCK GET: /orders/1 
Object {url: "/orders/1", type: "GET", isLocal: false, global: true, processData: true…}

Ember data tries a 2nd call

GET http://run.jsbin.com/services/%3CApp.Service:ember518:1%3E 404 (Not Found) 

First of all i dont understend why is the 2nd call? Service is sideloaded in my order JSON

var order = {
  "order" : {"id":1,"service":1,"qty_unit":4},
  "service":[{"id":1,"name":"ENG-GER","service_prices":[1,2]}],
  "servicePrices":[
    {"id":1,"qty_unit":4,"unit_price":3},
    {"id":2,"qty_unit":5,"unit_price":4}
  ],
  "qtyUnits":[
    {"id":4,"name":"character"},
    {"id":5,"name":"word"},
    {"id":6,"name":"sentence"}   
  ]
};

And why tries ember-data call the record App.Service:ember518:1 instead of its id "1"?

Here is the JsBin

http://jsbin.com/finahuna/1/edit

Was it helpful?

Solution

The problem was your setQtyUnits method. You were passing service model rather than just id as expected by your mock endpoint. ember518 is the ember generated name of service model instance in this case which was getting passed rather than id. Modified method is -

setQtyUnits:function(){

        var service_id = this.get('model.order.service.id');
        if (service_id !== null)
        {
          var self = this;
          //find returns a promise
          this.store.find('service',service_id).then(function(service){
            //on success
            var servicePrices = service.get('service_prices');
            var qtyUnits = servicePrices.mapBy('qty_unit');
            console.log(qtyUnits);
            self.set('qtyUnits', qtyUnits);
          });
        } else {
          this.set('qtyUnits', null);  
        }

  }.observes('model.order.service')

Here is the modified bin - http://jsbin.com/finahuna/4/edit

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top