Load a model's relations (hasMany, belongsTo) automatically

This is probably a most noob-ish question.

I’ve defined two models, Quote and Author, with

  • Quote belongsTo Author
  • Author hasMany Quotes
var Quote = DS.Model.extend({
	text: DS.attr('string'),
	author: DS.belongsTo('author')
});
export default Quote;

(I’m using Ember App Kit, BTW)

var Author = DS.Model.extend({
	name: DS.attr('string'),
	quotes: DS.hasMany('quotes')
});

I’m not using EAK’s API Stub, I have a very basic REST API that answers to

  • /quotes
  • /quote/:id
  • /authors
  • /author/:id

I load the models in the routes :

// quotes route
model: function() {
  return this.store.find('quote');
}

// authors route
model: function() {
  return this.store.find('author');
}

(plus routes with dynamic segments for both Quotes and Authors).

When I hit my app’s quotes route, Ember Data actually hits /quotes/ on the REST API and I get a JSON like this :

{
  "quote": [
    {
      "id": 0,
      "author_id": 0,
      "text": "Nothing is impossible, the word itself says 'I'm possible'!"
    },
    {
      "id": 1,
      "author_id": 1,
      "text": "You may not realize it when it happens, but a kick in the teeth may be the best thing in the world for you"
    },
    {
      "id": 2,
      "author_id": 3,
      "text": "Even the greatest was once a beginner. Don't be afraid to take that first step."
    },
    {
      "id": 3,
      "author_id": 2,
      "text": "You are afraid to die, and you're afraid to live. What a way to exist."
    }
  ]
}

Since I have declared the Quote belongsTo Author relationship, I was expecting Ember Data to be able to automagically retrieve each Quote’s Author.
However, if I understand correctly what I’ve read here, the JSON returned by my server should make this information obvious to EmberData. Is that correct ?

If not, what is the right way to load a model and the related data ?

I’ve tried with authorId instead of author_id (in the JSON returned by the server), to no avail.

I’ve also tried something like this route :

// quotes route
model: function() {
  var store = this.store;
  return store.find('quote').then(function(quote) {
    return store.find('author', quote.authorId) 
  };
}

Any clue welcome ! Thanks

2 Likes

Have you tried using “author” instead of author_id? That should work.

Something else to note, It’s not going to call and get the author data unless you try to output it somewhere. So you’d need to actually display it somewhere in your template or request it in your route or controller to actually have it make that call

Thanks @atc and @jakecraige.

I was actually trying to output data from author in my templates, but I was confused with naming conventions.

Switching from author_id to author did the trick. So I guess this is some kind of rule, that foreign keys should be named after the table they’re pointing at ?

Should I close this topic ? (How ?)