Reputation: 9082
I am using Ember Data 1.0 (beta 1) and am somewhat confused by the default behavior of associations in ED.
Assume a Book
model that has many (hasMany
) chapters
with each chapter
belonging to (belongsTo
) a book. My expectation was that the instances of a book's chapters
property would automatically have a reference to the book instance through their belongsTo
association, but this appears not to be the case. Is this indeed the default behavior in Ember Data or am I overlooking something?
If this is indeed the default behavior, does this mean that I need to create a custom serializer to accomplish this?
Upvotes: 0
Views: 635
Reputation: 1081
No ember-data will not do this for you but it should be possible to achieve. In both cases ember-data will sideload those properties. (In past versions you could setup a mapping so those would be embedded, but you no longer can do this) In your example you would have the following:
App.Book = DS.Model.extend({
chapters: DS.hasMany('Chapter')
});
App.Chapter= DS.Model.extend({
book: DS.belongsTo('Book')
});
Once those are setup ember-data by default will look for a data structured like this:
{
"book": {
"id": "1"
"chapters": ["1", "2", "3"]
},
"chapters": [
{
"id": "1",
"book": "1"
},
{
"id": "2",
"book": "1"
},
{
"id": "3",
"book": "1"
}
]
}
If your data is not in that format and you can not change it then you can extend the extractSingle or extractArray methods on the serializer for that type. At the bottom of this link you can find some more info on that. Also remeber it looks for it in camelcase so you may also need to normalize the json object as well.
Upvotes: 4