Matthew Sumner
Matthew Sumner

Reputation: 346

Ember data has many relationships

This is a question concerning my understanding.

In rails, when you setup a has_many-belongs_to association between two models, parent and children, the id is stored on only the children. If you want to find a child's parent, the database is queried using the id on the child. To find all a parents children the database is queried for all the records with a parent_id matching the current parent. Rails is my backend so this is what ember-data is interacting with.

Associations in ember-data seem to need to be setup both ways and ids need to exist on both models. A model with a has_many relationship should have a array containing it's children's ids. However, this is not stored on the server side.

Client side using ember, I need to be able to list a parents children. However, I can't access this without iterating over all the children for every parent.

There's a fundamental mismatch here and I just want to make sure that I am implementing my application correctly. Should my ajax be returning an array of ids with each parent or Should I be filling these in client side?

Upvotes: 1

Views: 973

Answers (1)

ahmacleod
ahmacleod

Reputation: 4310

Including an ids array for a hasMany relationship in your JSON is, strictly-speaking, optional. In practice it is essential because without it Ember-Data will only be able to find those associated records that have already been loaded.

For example, if you have

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

App.Comment = DS.Model.extend({
  post: DS.belongsTo('App.Post')
});

and you omit the comment_ids array in the post JSON, then you will need to manually call App.Comment.find() to load ALL comments before post.get('comments') will be guaranteed to contain all of the comments associated to a given post.

If you include the comment_ids array in the JSON for post, then Ember-Data will make a subsequent request for the comments it has not yet loaded.

Upvotes: 4

Related Questions