mardi 1 décembre 2015

Single route with dynamic segments coming from two different models

I have a Project model that belongsTo an Account model. Both of these models have permalinks used to generate pretty URLs. The Project permalinks are unique when scoped to their parent Account, so I need both permalinks to resolve the actual Project.

I am having trouble implementing a route serialize method to fill in the dynamic segments using both models.

Here's the route with dynamic segments:

this.route('tasks', {path: 'p/:account_permalink/:project_permalink/board'});

The tasks route has this serialize method:

serialize: function(project) {
  return {
    account_permalink: project.get("account.permalink"), 
    project_permalink: project.get("permalink")
  };
}

When I use this in a link-to, the account_permalink segment comes back as undefined:

{{#link-to "tasks" project}}
  {{project.account.name}}: {{project.name}}
{{/link-to}}

Results in:

<a id="ember688" href="/p/undefined/first-project/board" class="ember-view">
  KappenCo: First Project
</a>

The interesting thing is that if I use account.id instead of account.permalink, the dynamic segment is filled in with the id:

serialize: function(project) {
  return {
    account_permalink: project.get("account.id"), 
    project_permalink: project.get("permalink")
  };
}

Results in:

<a id="ember619" href="/p/1/first-project/board" class="ember-view">
  KappenCo: First Project
</a>

This smelled like an async loading issue, so I tried using promises to load the account first:

serialize: function(project) {
  project.get("account").then((a) => {
    return {
      account_permalink: a.get("permalink"), 
      project_permalink: project.get("permalink")
    };
  });
}

But it results in an error, a is always null:

TypeError: Cannot read property 'get' of null

There are lots of examples of filling multiple dynamic segments from the same model, but nothing that requires two different models to collaborate in filling the segments. This has been so difficult that I must be using the framework incorrectly, how do I achieve this the ember way?

The app is using Ember 1.13.7 and ember-data 1.13.9 in case that's a source of the problem.




Aucun commentaire:

Enregistrer un commentaire