Sequelize.js' association are not rendered on the page
-
20-06-2021 - |
Question
I have two models.
var self = {
User: sequelize.define('user', {
id: {type: Sequelize.INTEGER,primaryKey: true,autoIncrement: true},
name: {type: Sequelize.STRING,allowNull: false}
}),
Role: sequelize.define('role', {
id: {type: Sequelize.INTEGER,primaryKey: true,autoIncrement: true},
name: {type: Sequelize.STRING,allowNull: false}
})
}
I have also specify association between them.
self.User.belongsTo(self.Role);
Part of controller user.js:
list: function(req, res){
models.User.findAll({offset: offset, limit: limit}).success(function (users) {
if (req.params.format == 'html') {
res.render('admin/user/list.html', {
title: 'Users',
layout: layout,
users: users
});
} else if (req.params.format == 'json') {
res.json(users);
}
}
In view list.html:
<% users.forEach(function(user){ %>
<tr>
<td><%= user.id %></td>
<td><a href="/admin/user/<%= user.id %>/show.html"><%= user.name %></a></td>
<td><%= user.getRole().name %></td>
</tr>
<% } %>
If we call /list.html We obtained undefined role on page for each user.
And if we call /list.json we obtain:
[{"id":1,"name":"user1", "role_id":1},
[{"id":2,"name":"user2", "role_id":1},
[{"id":3,"name":"user3", "role_id":2},
...
How do I get the role for each user in list.html and in json response? Or maybe there is some better way?
Thanks.
Solution
The reason for not getting the associated role is the fact, that getting the role of that user is handled asynchronously. This means 1.) that you need to use user.getRole().success(function(role){})
and 2.) that you need to read the role in the controller because EJS isn't capable of handling asynchronicity. Hope that helps :)
OTHER TIPS
You need to call
models.User.findAll({offset: offset, limit: limit, include: [models.Role]})
see http://sequelizejs.com/documentation#models-eager-loading for more details