Ember Data loading hasMany relation doesn't work in Ember App Kit (EAK)

194 Views Asked by At

I'm trying to set up a hasMany relationship between two models and a hasOne (belongsTo in the current version of Ember Data) between the hasMany and hasOne.

I'm working with Ember Data and have a made a RESTful API that works according to Ember's conventions. All the classes can be queried individually.

Bookmark    = hasMany   -> Termbinding
Termbinding = belongsTo -> Term
Term        = belongsTo -> Termbinding

So the goal is to fetch a Bookmark and get the Terms that are attached to it through the Termbinding. I would already be pretty happy to get the Bookmark to Termbinding relation working. I went through all questions posted on here, sadly enough that didn't work.

Router.js

var Router = Ember.Router.extend();

Router.map(function() {

   this.resource('bookmarks', { path:'bookmarks'});
   this.resource('bookmark', { path:'bookmarks/:bookmark_id' });

   this.resource('termbindings', { path:'termbindings' });
   this.resource('termbinding', { path:'termbindings/:termbinding_id' });

});

export default Router;

Bookmark.js

var Bookmark = DS.Model.extend({
   url: DS.attr('string'),
   description: DS.attr('string'),
   visits: DS.attr('number'),
   termbinding: DS.hasMany('termbinding')
});

export default Bookmark;

Termbinding.js

var Termbinding = DS.Model.extend({
   bookmarkId: DS.attr('number'),
   termId: DS.attr('number'),
   termOrder: DS.attr('number'),
   bookmarks: DS.belongsTo('bookmark')
});

export default Termbinding;

I hope someone can help me because this is preventing me from using Ember for my bookmark application. Thanks in advance.

1

There are 1 best solutions below

0
On

It might be wise to explicitly specify your inverses, i.e.

var Termbinding = DS.Model.extend({
  bookmarkId: DS.attr('number'),
  termId: DS.attr('number'),
  termOrder: DS.attr('number'),
  bookmarks: DS.belongsTo('bookmark', { inverse: 'termbinding' })
});

export default Termbinding;

var Bookmark = DS.Model.extend({
  url: DS.attr('string'),
  description: DS.attr('string'),
  visits: DS.attr('number'),
  termbinding: DS.hasMany('termbinding', { inverse: 'bookmarks' })
});

export default Bookmark;

Ember Data will try to map inverses for you, however, it is not without faults. It could possibly be that your pluralization of 'bookmarks' on a DS.belongsTo relationship is throwing off its automatic inverse mapping. Typically for belongsTo you would use the singular, 'bookmark'. Conversely, your hasMany would be termbindings: DS.hasMany('termbinding')

Also, if you could show where you're invoking the models that would be greatly appreciated. Typically I find that creating a JSbin at emberjs.jsbin.com helps me isolate the problem and also provides a collaborative space to debug and experiment.