PaulUithol/Backbone-relational — Issue #61: Confusion about fetching related models
Author: petercpw
Created: 2012-01-04 08:14:09+00:00
State: open

I have a model called Client and a model called Jobs. Each Client can have many Jobs, but each Job can only belong to one Client. So Client HasMany Jobs and Jobs HasOne Client.

Anyway, I have a Job Collection that fetches data from my server. The server returns a JSON object like so:

[ {
id: 5,
due_date: 01-05-2012,
Client:
{
id: 100,
name: James,
phone: 123-123-1234
}
}]

However, backbone-relational doesn't seem to be able to parse the relation. I get an error when I call jobList.at(0).get('Client').get('name);

Here's my code:

Client = Backbone.RelationalModel.extend({
relations: [{
type: Backbone.HasMany,
key: 'Jobs',
relatedModel: 'Job',
collectionType: 'JobCollection',
reverseRelation: {
key: 'Client',
includeInJSON: 'id'
}
}]
});

Job = Backbone.RelationalModel.extend({
});

JobCollection = Backbone.Collection.extend({
url: baseURL+'app/jobs/',
model: Job
});

var jobsList = new JobCollection();
jobsList.fetch({
data: { user_id: 1},
success: function(model, resp){
alert(jobsList.at(0).get('Client').get('name'));
}
});