2
votes

Just getting started with Ember and have a question about the ember way to handle a common pattern.

I have a have the following router.js:

export default Router.map(function() {
  this.resource('posts', function(){
    this.route('post', { path: "/:title" });
    this.route('new');
  });
});

I'm wondering how to use the value of the post title as the dynamic segment so that post urls show up as /posts/my-post-title-here

I'm confused as to which model this is being looked up on or if there is an "ember way" to handle this common patter (besides using the posts_id for the dynamic segment).

All my posts are defined in routes/posts.js, so I thought I simply needed to lookup the values in this route inside of my routes/post.js route, like this:

export default Ember.Route.extend({
  model: function(params) {
    var posts = this.modelFor('posts')
    return posts.findBy('title', params.title);
  }
});

I'm seeing the /posts/:title route in my Ember inspector, but in the browser, the links are all undefined ( /posts/undefined ).

{{#each model as |post|}}
  {{#link-to "posts.post" model }}
    <li>{{post.title}}</li>
  {{/link-to}}
{{/each}}

I'd love any advice about the proper way to handle this situation or explanations about how Ember looks up values for nested routes.

1

1 Answers

2
votes

You need to setup a serializer on your routes/post.js, like this:

// routes/post.js

export default Ember.Route.extend({
  model: function(params) {
    var posts = this.modelFor('posts')
    return posts.findBy('title', params.title);
  },
  serialize: function(model) {
      return { post_slug: model.get('title') };
  }
});

See Dynamic Segments