Reputation: 777
I'm working with simple restaurant menu at the moment and I receive the following JSON from the server:
[
{
"id": 251,
"name": "Borsch",
"category_id": 47,
"price": "135.0",
"photo": {
"origin": "/path/to/origin.png",
"resize": "/path/to/resize.png"
}
},
// A lot of other dishes
]
As you can see I have a photo
which is a complex object. On emberjs.com they suggest to use embedded models for this. Ok, so far so good, and I'd decided to create following models:
App.Dish = DS.Model.extend({
name: DS.attr('string'),
price: DS.attr('number'),
category_id: DS.attr('number'),
photo: DS.belongsTo('photo')
});
App.Photo = DS.Model.extend({
origin: DS.attr('string'),
resize: DS.attr('string')
});
but it didn't work even when I added this code
DS.RESTAdapter.map('App.Dish',{
photo: {
embedded:'always'
}
});
So after that I googled a bit and came with this link where explained that they don't support embedded records anymore.
After some thinking I'd decided to bring photo.origin
and photo.resize
to the top level of JSON inside RESTSerializer and now I have this fully working model:
App.Dish = DS.Model.extend({
name: DS.attr('string'),
price: DS.attr('number'),
category_id: DS.attr('number'),
photo_origin: DS.attr('string'),
photo_resize: DS.attr('string')
});
and this slightly transformed with RESTSerializer JSON:
{
"dishes":
[
{
"id": 251,
"name": "Borsch",
"category_id": 47,
"price": "135.0",
"photo_origin": "/path/to/origin.png",
"photo_resize": "/path/to/resize.png"
}
},
// A lot of other dishes
]
}
Now I have several questions. Is my approach acceptable? If not how do I need to process complex JSON with nested objects? If yes, how do I have to process some even more complex JSON with deeply nested (like five levels) objects? Why did ember stop supporting embedded models?
Upvotes: 0
Views: 124
Reputation: 5804
Instead of having embedded values, you have relations like you created in the first example.
Now i don't know if you have any control over the JSON output of the server, but by using relations EmberJS would expect your JSON to be structured this way (Depending on your EmberData Adapter).
{
dish: [{
"id": 251,
"name": "Borsch",
"category_id": 47,
"price": "135.0",
"photos": [1]
}],
photo: [{
"id": 1
"origin": "/path/to/origin.png",
"resize": "/path/to/resize.png"
}]
}
Now Ember will create the the Dish, and the Photo, and bind them together.
I think this would be the correct way to handle it.
Upvotes: 1