ember.jsember-routerhtmlbars

EmberJS 2.7 assertion failed passing id of nested object


EmberJS 2.7 Error: Assertion Failed: id passed to findRecord() has to be non-empty string or number

app/templates/products/index.hbs: [inside the model/each loop I have this line]:

{{#link-to 'categories.edit' product.category.id}}<a href="">{{product.category.name}}</a>{{/link-to}}

app/router.js: [I have these routes defined]:

  this.route('products', function() {
    this.route('new');
    this.route('edit', { path: '/:product_id/edit' });
  });

  this.route('categories', function() {
    this.route('new');
    this.route('edit', { path: '/:category_id/edit' });
  });

It works when editing a product. But throws the above error when trying to edit a category.

If I delete the 'categories/edit' route and add this route instead:

this.route('category', { path: '/categories/:category_id/edit' });

and change the template to use that:

{{#link-to 'category' product.category.id}}<a href="">{{product.category.name}}</a>{{/link-to}}

Then it works. I understand why this second one works. But why does the first one not work?

EDIT: Here are the models

app/models/product.js:

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
  category: DS.belongsTo('category', { async: true })
});

app/models/category.js:

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  products: DS.hasMany('product')
});

Solution

  • Fixed. Where you put the findRecord on the model is important. I had this code in the categories route. Moving it to the correct file solves the problem.

    app/routes/categories.js:

    import Ember from 'ember';
    
    export default Ember.Route.extend({
        model(params) {
            return this.store.findRecord('category', params.category_id);
        },
    });
    

    SOLUTION:

    app/routes/categories.js:

    import Ember from 'ember';
    
    export default Ember.Route.extend({
    });
    

    app/routes/categories/edit.js:

    import Ember from 'ember';
    
    export default Ember.Route.extend({
        model(params) {
            return this.store.findRecord('category', params.category_id);
        },
    });