Canttouchit
Canttouchit

Reputation: 3159

Ember.js - Nested resources Template Error: "Cannot call get with 'id' on an undefined object"

My Code - JSbin

I wanted to add a resource (e.g. sites/5/posts/ -> posts is the new resources I added).

WebApp.Router.map(function () {
    this.resource('sites', { path: '/' } , function() {
        this.resource('site', { path: '/sites/:site_id'} ,  function() {
            this.resource('posts', { path: 'posts'

            }); //posts

        }); //sites/id 

        this.route('new', {path: 'new'});

    });

});

My template:

<script type="text/x-handlebars" data-template-name="sites">
<ul>
    {{#each site in controller}}
    <li>
        {{#linkTo 'site' this}} {{site.siteName}} {{/linkTo}}
        {{#linkTo 'posts'}} > {{/linkTo}}
    </li>
    {{/each}}

</ul>
{{#linkTo 'sites.new'}} ADD NEW WEBSITE {{/linkTo}}

{{outlet}}

I want to each list item to have the link that points sites/:site_id/posts/. Adding the line {{#linkTo 'posts'}} > {{/linkTo}} to the template generates the error: Assertion failed: Cannot call get with 'id' on an undefined object.

What did I do wrong?

Upvotes: 1

Views: 1133

Answers (1)

Sherwin Yu
Sherwin Yu

Reputation: 3230

I made a few changes:

  1. You shouldn't set the id attribute on your models, so I removed the id: DS.attr('integer') lines from your Site and Post models.
  2. The line causing the problem is your second linkTo helper:

    {{#linkTo 'posts'}} > {{/linkTo}}

    The posts route (actually posts.index, which Ember autogenerates) expects a site object because it's nested under the site resource. The path you're trying to link to is sites/:site_id/posts/, so you need to provide the a site, otherwise it doesn't know which site's posts to display.

So you're getting an "cannot call id on undefined object" that prevents the template from rendering, I assume, because the template's linkTo helper tries to create a link with an id, but it has no object to serialize.

In short, all you to do is add back the argument to the linkTo helper: {{#linkTo 'posts' site}}. See here: http://jsbin.com/axaqix/13/edit

Upvotes: 2

Related Questions