Question

I am experimenting with a Ember app using ember-data and a node.js backend serving data from MySQL using Sequelize.js.

My problem: If I have a Comment model associated to a Post model through hasMany the expected JSON by ember-data looks like

{
  "post": {
    "comment_ids": [1, 2, 3]
  }
}

What would be the best way to query / generate this JSON without expensive loops etc. using sequelize?

The Comment model has a foreign key with the post_id.

Was it helpful?

Solution

I went for implementing it like:

// include comments
Post.all({
  where: "..",
  include: [Comment]
}).success(function(posts) {
  // collect IDs
  _.each(posts, function(element) {
    element["comments"] = _.pluck(element.comments, 'id');
  });
});

OTHER TIPS

I'd suggest passing the buck to the client. You can set up a custom serializer client side that reformats the data into the expected format for ED. Additionally ED is expecting it in this format:

{
   "post": {
     "comments": [1, 2, 3]
   }
}

App.Post = DS.Model.extend({
   comments = DS.hasMany('comment')
});

or if you choose to include the comments in the response

{
 "post": {
   "id": 1
   "title": "Rails is omakase",
   "comments": ["1", "2"],
   "_links": {
      "user": "/people/dhh"
   },
 },

 "comments": [{
   "id": "1",
   "body": "Rails is unagi"
  }, {
   "id": "2",
   "body": "Omakase O_o"
  }]
}

You can read more about it here: https://github.com/emberjs/data/blob/master/TRANSITION.md

At some point, someone is going to have to loop (or iterate) and it isn't an uncommon practice to iterate through your result set to build up your response (or serialize your response client side).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top