@Rick_Meertens wrote:
Hello guys,
I tried different solutions/hacks(which I will list here) to load data from a hasMany relationship and view it in a nested route.(/posts/{post_id}/comments) I'am using a REST API server, without JsonAPI.
I hope you guys can help me out.
My situation:
I am trying to get a 'post' loaded in post.hbs with multiple 'comments' loaded in comments.hbs on a single page.
Models
Post.js
export default DS.Model.extend({ comments: DS.hasMany('comment'), messsage: DS.attr() });
Comment.js
export default DS.Model.extend({ post: DS.belongsTo('post'), date: DS.attr() });
Nested route
/posts/{post_id}/comments
REST Server API
GET /posts/{id} { "id" : "1", "message" : "hello" }
GET /comments?post={post_id} [{ "id" : "324", "date" : "01012015" }, { "id" : "24", "date" : "02012015" }]
Solution one
/routes/posts.js
model(params) { return this.store.findRecord('post', params: post_id ); }
/routes/posts/edit/comments.js
model() { let post=this.modelFor('posts/edit'); return this.store.query('comment', { post: post.id }); }
This solution is working, but new added comments(using the route /posts/{id}/comments/new) are only visible after a reload of the page.
Solution two
/routes/posts.js
model(params) { return this.store.findRecord('post', params: post_id ); }
/routes/posts/edit/comments.js
model() { let post=this.modelFor('posts/edit'); let comments=this.store.query('comment', { post: post.id }); post.set('comments',comments); return post.get('comments'); }
This solution is working, but when the user navigates away and back through 'link-to' helpers the 'comments' are not shown, while they are still loaded in the store...
Solution three
/routes/posts.js
model(params) { return this.store.findRecord('post', params: post_id ); }
/routes/posts/edit/comments.js
model() { let post=this.modelFor('posts/edit'); return post.get('comments'); }
/serializers/post.js
normalizeResponse(store, primaryModelClass, payload, id, requestType) { .... commentLink='/comments?post='+post_id result.links={ 'comments' : commentLink }; ... }
This solution works perfectly, but adding links to the payload in the REST serializer seems like a hack to me.
Posts: 1
Participants: 1