With and without dynamic segments issue


#1

Hello,

As a preface, I’m still a bit new to EmberJS, and as such, I haven’t gotten a full understanding of many of the Ember concepts.

I’m having a bit of trouble figuring out how to correctly use nested routes and dynamic segments. I’m going to use friends as an example of what I’m trying to do.

When the user goes to /friends (ie, routes/friends.js), he’s presented a dropdown of all available friends to choose from. Once he chooses a friend and clicks Submit, a summary (routes/friends/show) of that friend appears. But I want to keep the dropdown that I originally had so someone can choose a new friend from the friend detail page. The problem I’m having is how to get the :friend_id dynamic segment to be selected upon page load.

So router.js looks like:

  this.route('friends', function() {
    this.route('show', {
      path: ':friend_id'
  });

routes/friends.js is:

model: function(params) {
    return this.store.findAll('friend');
},

routes/friends/show.js is:

model: function(params) {
    return this.store.find('friend', params.friend_id);
}

templates/friend.js is:

<form {{action "submitQuery" on="submit"}}>
    <select name="friend" onchange={{action (mut friend) value="target.value"}}>
        <option value="" disabled>Please select a friend</option>
        {{#each model as |item|}}
            <option value="{{item.id}}" selected={{eq friend item.id}}>{{item.displayName}}</option>
        {{/each}}
    </select>
    <button type="submit">Submit</button>
</form>
<hr>
{{outlet}}

I also have a controller for friends, but I don’t think that’s relevant to the issue at hand. When you go to /friends, nothing will be selected and the dropdown will simply say “Please select a friend”, and nothing will be rendered in {{outlet}}. You can choose a friend and the details will be displayed. But if you go directly to, say, /friends/25, the friends details will show up, but the dropdown will be at its default state (“Please select a friend”) because routes/friends.js does not have a dynamic segment, so it doesn’t know of :friend_id.

So what would be the proper way for me to organize my code for my scenario here?


#2

You can do something like this:

/routes/sites.js

import Ember from "ember";

export default Ember.Route.extend({
  model: function() {
    return this.store.findAll('site');
  },

  redirect: function(model, transition) {
    if (transition.targetName === 'sites.index') {
      this.transitionTo('site', model.sortBy('sort').get('firstObject'));
    }
  }

});