I’m using backbone.js and backbone relational 0.5.0 with a Rails 3.2 backend. I have a Card model which has_many Notes.
Here are my JS models and collections:
Workflow.Collections.Cards = Backbone.Collection.extend({
model: Workflow.Models.Card,
url: '/cards'
});
Workflow.Models.Card = Backbone.RelationalModel.extend({
modelName : 'card',
urlRoot : '/cards',
relations: [
{
type: Backbone.HasMany,
key: 'notes',
relatedModel: 'Workflow.Models.Note',
collectionType: 'Workflow.Collections.Notes',
includeInJSON: false,
reverseRelation: {
key: 'card',
includeInJSON: 'id'
}
}]
});
Workflow.Collections.Notes = Backbone.Collection.extend({
model: Workflow.Models.Note,
url: '/cards/74/notes' // intentionally hard-coded for now
});
Workflow.Models.Note = Backbone.RelationalModel.extend({
modelName : 'note',
urlRoot : '/notes'
});
Normal fetching works great, but when I try fetchRelated in the console, I get an empty array:
card = new Workflow.Models.Card({id: 74}) // cool
card.fetch() // hits the sever with GET "/cards/74" - works great
card.fetchRelated('notes') // [] - didn't even try to hit the server
What’s weird is that this works:
card.get('notes').fetch() // cool - GET "/cards/74/notes"
I could use that method and parse the response text, but it feels really dirty.
Anyone know what I’m missing here?
Thanks in advance, this one is really torturing me!
Stu
I should have posted my solution a while back – there might well be a better way, but this is the convention I’ve gone with:
All of the following code is in the card view (which is where the notes are displayed).
First, I bind a
renderNotesmethod to the'reset'event on the card’s notes collection:I also bind to the
'add'on that collection to call a singularrenderNote.The renderNotes and renderNote methods work like this:
Then, the last piece of the puzzle is to actually hit the server up for the card’s notes (which will in turn fire the
'reset'event I bound to above). I do this in the card view’srendermethod:As @user1248256 kindly helped me work out in the comments on my OP, the confusion was mainly in that I expected
fetchRelatedto pull down lazy-loaded records – that’s actually not the case.As a side-note, this view is actually a modal and be opened and closed (removed from the page). To prevent the zombie events problem described in this excellent post, I also manually unbind the events mentioned above.