7

I have the following Emberjs Data model:

App.File = DS.Model.extend({
  like: DS.attr('boolean'),
  comments: DS.hasMany('App.Comment')
});

App.Comment = DS.Model.extend({
  file: DS.belongsTo('App.File'),
  comment: DS.attr('string')
});

And preload it with:

 App.store.load(App.File, {id: 1, like: false});

Now I thought, if I get the comments like this:

var f = App.store.find(App.File, 1);
var c = f.get("comments");

var c is a empty EmberArray and a request is send to the server. But I don't get a request? Why and how do I have to do it? I really don't wanna preload the comments.

Further more, if I add a comment, but also change the file simultaneously:

f.get("comments").createRecord({comment: "test"});
f.set("like", true);
App.store.commit();

Two requests are send to the server. But if I then return the following JSON (for the file):

{ "id": 1, like: true }

My first visible comment disappears again. Why? And what do I have to do?

Thanks for your help!

Mike Aski
  • 9,180
  • 4
  • 46
  • 63
lüku
  • 115
  • 6

2 Answers2

1

Regarding the first part of your question: You should populate the comments ids in the file's data:

App.store.load(App.File, {id: 1, like: false, comments: [1, 2, 3]});

So the comments will be lazy loaded when needed.

Regarding the second part: You certainly do not serialize the comment ids on the reply from your server, so the comments are reset, as you describe an empty comments list.

You should at least return the comments ids as shown just before... The two issues are linked.

Mike Aski
  • 9,180
  • 4
  • 46
  • 63
  • Thank's for the fast answer. Ok. Is there no other way? This way leads to much more sql-querys for data, which in most cases, I don't need. And it won't help for the second problem, because the first request to the server is the request for the file updated. And the second request is the add-comment request. Maybe it would work, if I add a second commit-command after the createRecord. – lüku Sep 11 '12 at 18:31
  • I would prefere the mechanisme used with findQuery. The first time you use the comments attribute, a findQuery would be passed to the server. – lüku Sep 11 '12 at 18:54
  • 1
    I ran into a similar issue. It would be nice if instead of requiring the ids for a findMany call, they would support fetching via a findQuery using the foreign key. I decided just to add a "getComments" method to my model that runs the findQuery. – jhorman Sep 11 '12 at 19:03
0

It looks like part of the answer to this is to use the DS.Adapter.findAssociation(...) method in your adapter. However, I'm having the same problem as you when the parent record is loaded again from the server--all the child records get zapped.

I've posted my own question to see if I can get this sorted out. If that question gets answered, it will probably also be the answer to yours.

Community
  • 1
  • 1
S'pht'Kr
  • 2,809
  • 1
  • 24
  • 43