I'm trying to list some posts with their related users. Each post has a title some text and a userId like this:
[{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"text": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}]
How can I relate my post model to the users model? It works like I tried it below but it's quick and dirty. Do I need to use backbone-relational? I just don't know if backbone-relation is an overkill for just one one-2-many relation in my application.
var fetchingPosts = BackboneApplication.request("post:entities");
var postsListLayout = new List.Layout();
$.when(fetchingPosts).done(function(posts){
$.each(posts.models, function(i, post){
var username = BackboneApplication.request("user:entity", post.get("userId"));
$.when(username).done(function(user){
post.set("name",user.get("name"));
});
});
var contactsListView = new List.Posts({
collection: posts
});
EDIT due to the question my post model looks like this:
Entities.Post = Backbone.Model.extend({
url : "url_to_rest_api",
idAttribute : 'id'
});
EDIT 2: Is this following parse function possible for the fact that I'm not able to change my rest api.
parse: function(response) {
user = BackboneApplication.request("user:entity", response.userId)
this.user = new User(user);
return response'
}
One option is to have your posts service return fully loaded "Post" models that look like:
[{
//not just an id anymore
"user": {"id":1, "username":"Fred", "email":"bob@bob.com"},
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"text": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}]
Then in your Post model's parse method you can do the following:
parse: function(response) {
//convert raw user json to backbone model
response.user = new User(response.user);
return response'
}
This avoids the relational dependency, but requires your rest endpoint to load user data with all post data. You could have your endpoints be specific but have your service layer be general so the concept of post and user are still loosely coupled
//pseudo
def getPost(id) {
def post = postService.getPost(id);
post.user = userService.getUser(post.userid)
render post as json
}