0

I would like to redirect an incomplete URL to a complete correct URL:

http://localhost/product/12/a-single-pr -> http://localhost/product/12/a-single-product-name

The problem is that the model hook is called twice instead of one, making two identical requests to retrieve a single object. Any clues?

routes/product.js

import Ember from 'ember';

export default Ember.Route.extend({
  afterModel(model, transition) {
    let formatted = model.get('formatted');

    if (transition.params.product.formatted !== formatted) {
      let path = '/product/' + model.id + '/' + formatted;
      this.replaceWith(path, model);
    }
  },
  model(params) {
    return this.get('store').findRecord('product', params.product_id);
  }
});

router.js

...

Router.map(function() {
  this.route('product', {path: '/product/:product_id/*formatted'});
});

...
Caio
  • 3,178
  • 6
  • 37
  • 52

1 Answers1

1

Ember is working as expected.

You hit the product route, it fetches the model and then in the afterModel, it redirects back to the product route, which will kick off the route lifecycle again, meaning it will fetch the model again and then call afterModel again.

A different way to approach the problem would be to replace to URL in afterModel instead of redirecting back to the same route.

See this StackOverflow answer in order to accomplish that: https://stackoverflow.com/a/3503206/2891906

Community
  • 1
  • 1
GManProgram
  • 161
  • 2
  • 11