Kasper Tidemann
Kasper Tidemann

Reputation: 488

How to handle associations between records in ember-data

Explanation:

Working with ember-data, a lot of different scenarios pop up that don't all seem to match the way the internals work at this point. First off, some data:

{ "post":
  {
    "id": "60",
    "title": "Hello, Stack Overflow friends!",
    "comments": []
  }
}

Say the above is data from the database.

Then, a post record is fetched on client 1 and client 2 by calling post = App.Post.find(60) on each client, respectively. So far, they both have the same post record - loaded with an empty comments array.

At a later time, a comment is created on client 2. This is done by calling comment = App.Comment.createRecord({text: "Why, hello there.", post: post}).

The comment data is then saved server-side, looking like so:

{ "comment":
  {
    "id": "80",
    "text": "Why, hello there.",
    "post_id": "60"
  }
}

At this point, client 2 is up-to-date - since this is where the comment was created - but client 1 is out-of-sync, because it does not know of the new comment.

Now, client 1 may become aware of the newly created comment one way or another (via XHR or WS).

Once client 1 knows the id, a comment record is fetched by calling comment = App.Comment.find(80).

... Yet calling post.get('comments') on client 1 results in 0 comments. Even though the new comment was fetched successfully, no association between the comment and the post was made.

Problem:

Note 1: this does not happen because on client 1, the post record was originally loaded with comments: []. If the array had contained the comment id, 80, this would have worked (besides the fact that the comment did not exist at load time).

Note 2: I can add the association manually by calling post.get('comments').addObject(comment) on client 1, but this dirties the post record and doesn't seem like a proper way of handling this.

Question:

Upvotes: 1

Views: 264

Answers (1)

Cyril Fluck
Cyril Fluck

Reputation: 1581

When you load a record that has a belongsTo relationship, ember data doesn't currently update the "parent" record of the relationship.

One way to solve this problem in your case is to sideload the "parent" record. In your case, you would send (via XHR or WS) the comment and the post.

There's an open ticket for this problem https://github.com/emberjs/data/pull/695

Upvotes: 1

Related Questions