I have a question regarding associations in Sails.js version 0.10-rc5. I am creating an application in which several models are connected to each other, and I have come to the point where I need to somehow associate associations.
There are three parts:
At first there is something like a blog post written by a user. In a blog post, I want to show relevant user information, such as username. Now everything works fine. Until the next step: I'm trying to show comments related to this post.
Comments are a separate model called Comment. Each of them also has an author (user) associated with it. I can easily show the list of comments, although when I want to display the user information associated with the comment, I cannot figure out how to populate the comment with user information.
In my controller, I am trying to do something like this:
Post .findOne(req.param('id')) .populate('user') .populate('comments') // I want to populate this comment with .populate('user') or something .exec(function(err, post) { // Handle errors & render view etc. });
In the "show" action of my message, I try to get information similar to this (simplified):
<ul> <%- _.each(post.comments, function(comment) { %> <li> <%= comment.user.name %> <%= comment.description %> </li> <% }); %> </ul>
However, comment.user.name will be undefined. If I try to just access the user property, for example comment.user, it will show its ID. Which tells me that it does not automatically populate the user information with the comment when I link the comment to another model.
Any any ideals to solve this correctly :)?
Thanks in advance!
PS
For clarification, here's how I basically set up associations in different models:
// User.js posts: { collection: 'post' }, hours: { collection: 'hour' }, comments: { collection: 'comment' } // Post.js user: { model: 'user' }, comments: { collection: 'comment', via: 'post' } // Comment.js user: { model: 'user' }, post: { model: 'post' }