lundi 30 mars 2015

Display belongsTo category for a product

I render a product table at http://localhost:4200/products which should include the category of each product but doesn't.


Screenshot of the product table.


The template code:


app/templates/products/index.hbs



[...]
<tbody>
{{#each product in model}}
<tr>
<td>
{{product.name}}
</td>
<td>
{{product.category.name}}
</td>
[...]


Why doesn't {{product.category.name}} display the product.name? How can I fix it?


The Application



ember new shop
cd shop
ember install:addon ember-cli-scaffold
ember g scaffold product name:string
ember g scaffold category name:string
ember g adapter application
ember g http-mock products
ember g http-mock categories


app/adapters/application.js



import DS from 'ember-data';

export default DS.RESTAdapter.extend({
'namespace': 'api'
});


app/models/product.js



import DS from 'ember-data';

export default DS.Model.extend({
name: DS.attr('string'),
category: DS.belongsTo('category')
});


app/models/category.js



import DS from 'ember-data';

export default DS.Model.extend({
name: DS.attr('string'),
products: DS.hasMany('product')
});


server/mocks/products.js



module.exports = function(app) {
var express = require('express');
var productsRouter = express.Router();

productsRouter.get('/', function(req, res) {
res.send({
'products': [
{"id":1,"name":"Orange"},
{"id":2,"name":"Banana"},
{"id":3,"name":"Potato"}
]
});
});
[...]


server/mocks/categories.js



module.exports = function(app) {
var express = require('express');
var categoriesRouter = express.Router();

categoriesRouter.get('/', function(req, res) {
res.send({
'categories': [
{"id":1,"name":"Fruits","products:":[1,2]},
{"id":2,"name":"Vegetables","products:":[3]}
]
});
});
[...]




Aucun commentaire:

Enregistrer un commentaire