Access a has-many relationship within template


#1

How do I access a has-many relationship and display it within a template?

I have the following simple models defined:

App.User = DS.Model.extend({
    name: DS.attr('string'),
    channels: DS.hasMany('channel')
});

App.Channel = DS.Model.extend({
    user: DS.belongsTo('user'),
    name: DS.attr('string'),
    status: DS.attr('string'),
    message: DS.attr('string')
});

From within my user template if I try this:

<script type="text/x-handlebars" data-template-name="user">
    <div class="row">
        <div class="col-md-6">
            <h1>User: {{name}}</h1>
            <div class="list-group">
                <div class="list-group-item">
                    Email: {{email}}
                </div>
                {{#each channel in channels}}
                    <div class="list-group-item">
                        Channel: {{channel.name}}
                    </div>
                {{else}}
                    <div class="list-group-item">
                        No channels
                    </div>
                {{/each}}
            </div>
        </div>
        <div class="col-md-6">
            {{outlet}}
        </div>
    </div>
</script>

No channels show up.

What am I doing wrong?


#2

Your code looks okay at first sight.

Do you see the data coming in your request’s response (network tab of your browser’s dev tools)? Or in the Ember inspector (data tab)?

Do you sideload it? Or do you load the the channels data asynchronously? (then add { async: true } in your hasMany relationship definition)

You could insert a {{channels.length}} to debug it.


#3

Turns out that { async: true } did the trick, thanks!