Skip to content

Instantly share code, notes, and snippets.

@bobey
Last active December 10, 2015 20:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bobey/4492260 to your computer and use it in GitHub Desktop.
Save bobey/4492260 to your computer and use it in GitHub Desktop.
I want to lazy load those post comments without embedding comment ids in my post GET JSON
// My models:
App.Post = DS.Model.extend({
content: DS.attr('string'),
comments: DS.hasMany('App.Comment')
});
App.Comment = DS.Model.extend({
content: DS.attr('string'),
post: DS.belongsTo('App.Post')
});
// My GET request JSON does look like the following:
{
"post": {
"content": "Some content"
}
}
// whereas ember-data is looking for something like this:
{
"post": {
"content": "Some content"
"comments": [1, 2, 3] // embedded comments ids
}
}
// How can I do something as the following somewhere in an ObjectController without using a findQuery:
this.get('content.comments') // do something whit those comments
// ... I tried the following trick:
App.Post = DS.Model.extend({
content: DS.attr('string'),
comments: function() {
return App.Comment.find({postId: this.get('id')});
}.property('id')
});
App.Comment = DS.Model.extend({
content: DS.attr('string'),
postId: DS.attr('number')
});
this.get('content.comments') // this line seems to work as expected
// But if I add a new comment associated to that post somewhere in a controller:
App.Post.createRecord({
postId: this.get('content.id')
})
// my post comments property isnt updated nor the findQuery cause findQuery returns AdapterPopulatedRecordArray
// What we want is a RecordArray that remains up to date even when we add new records to this post.
// Let's try with filter method instead of findQuery though:
App.Post = DS.Model.extend({
content: DS.attr('string'),
comments: function() {
postId = this.get('id');
return App.Comment.filter({post_id: postId}, function(data) {
return data.get('postId') == postId;
});
}.property('id')
});
this.get('content.comments') // this line seems to keep working as expected
App.Post.createRecord({
postId: this.get('content.id')
})
// And booom, we added a new record and our array almost immediatly contains it!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment