1
votes

I am working with Ember and Ember Data, and the JSON I get back from the server contains an embedded object array. I need to know what I am doing wrong. I have a JSBin with the code below:

http://emberjs.jsbin.com/faledu/6/edit?html,js,output

Currently, I am getting the following error:

Error while processing route: index Assertion Failed: Ember Data expected a number or string to represent the record(s) in the objects relationship instead it found an object. If this is a polymorphic relationship please specify a type key. If this is an embedded relationship please include the DS.EmbeddedRecordsMixin and specify the objects property in your serializer's attrs object. Error: Assertion Failed: Ember Data expected a number or string to represent the record(s) in the objects relationship instead it found an object. If this is a polymorphic relationship please specify a type key. If this is an embedded relationship please include the DS.EmbeddedRecordsMixin and specify the objects property in your serializer's attrs object.

I am using DS.EmbeddedRecordsMixin in my serializer, but it doesn't seem to be working. How can I use that JSON with Ember Data?

1

1 Answers

0
votes

You can add a custom array transform for ember-data to use and greatly simplify your code by eliminating the need for the EmbeddedRecordsMixin, etc.

http://emberjs.jsbin.com/warebi/1/edit

Here is an array transform I've used quite often in the past:

App.ArrayTransform = DS.Transform.extend({
  deserialize: function(serialized) {
    return (Ember.typeOf(serialized) === 'array') ? serialized : [];
  },

  serialize: function(deserialized) {
    var type = Ember.typeOf(deserialized);
    if (type === 'array') {
      return deserialized;
    } else if (type === 'string') {
      return deserialized.split(',').map(function(item) {
        return item.trim();
      });
    } else {
      return [];
    }
  }
});

But, I will say that you should really avoid fighting ember-data when it comes to structure. I've tried to force edge-case scenarios and ended up doing a lot more work than needed. If you can't modify your API to be more 'JSON API' friendly, I'd consider looking at other alternatives to ember-data or consider just using plain AJAX to handle things similar to the Discourse approach. At the end of the day, I'd just try to make sure your API works in the side-loading style or two separate requests using the async approach. Your life will be much easier.

"design": {
  "id": "1",
  "name": "test1",
  "description": "testing",
  "objects": [1, 2]
},
"objects": [
  {
    "id": 1,
    "name": "foo"
  },
  {
    "id": 2,
    "name": "bar"
  }
]

This is an old blog post, but the main concepts still apply if your use case needs to operate outside of the ember-data happy path - http://eviltrout.com/2013/03/23/ember-without-data.html