Search code examples
ember.jsember-router

Custom Dynamic Segment (NOT ID) - EmberJS


I want to have a dynamic segment path in Ember without using the :id attribute

As per the Ember Guides, I'm using the serialize method to achieve this.

Heres my Router:

App.Router.map(function() {
    this.resource("orders", function(){
        this.resource('order', { path: ':order_sequence'}, function(){
            this.route('edit');
        })
    });
});

And my Route:

var OrderRoute = Ember.Route.extend({
    model: function(params) {
        return this.store.find('order', params.order_sequence)
    },
    serialize: function(model) {
        return { order_sequence: model.get('sequence') };
  }
});

module.exports = OrderRoute;

However, my URL's still behave using the id attribute in the path instead of the sequence attribute..

Any ideas?


Solution

  • Is your browser caching something, because that's correct. Are you passing in the id instead of the sequence/model in any of your transitionTo/transitionToRoute/link-to?

    Oh, you aren't talking about the slug in the url, nor the route, you are talking about the id of your model. You need to create a serializer for that particular model and override the primary key

    App.OrderSerializer = DS.RESTSerializer.extend({
      primaryKey: 'sequence'
    });
    

    The Fixture Adapter has a constraint on defining the id, but you can lazily get around it by extending the fixture adapter and overriding a single method

    App.OrderAdapter = DS.FixtureAdapter.extend({
    
     fixturesForType: function(type) {
      if (type.FIXTURES) {
       var fixtures = Ember.A(type.FIXTURES);
       return fixtures.map(function(fixture){
    
        // aka we massasge the data a bit here so the fixture adapter won't whine so much
        fixture.id = fixture.sequence;
        var fixtureIdType = typeof fixture.id;
        if(fixtureIdType !== "number" && fixtureIdType !== "string"){
          throw new Error(fmt('the id property must be defined as a number or string for fixture %@', [fixture]));
        }
        fixture.id = fixture.id + '';
        return fixture;
       });
      }
      return null;
     },
    });