I am working on a backbone.js application with rails api which provides the json as shown:
[{
"title": "Da vinci Code",
"price": "50"
},
{
"title": "Some other name",
"price": "45"
}],
TODO:
- When a user visits the url “http://www.backboneapp.com/authors/1″ , it should display a list of books belonging to the author.
Progress:
– Server side-Rails [authorscontroller#show]
def show
@author = Author.find(params[:id])
@books = @author.books
respond_to do |format|
format.json { render :json => @books }
format.html
end
end
2.Client-side-Backbone.js
Router:
routes: {
'authors/:id': 'showauthor'
},
showauthor: function(id) {
$('#container').empty();
window.available_books = new AvailableBookList({
id: id
});
this.availablebooklistview = new AvailableBookListView({
id: id,
collection: available_books
});
$('#container').append(this.availablebooklistview.render().el);
}
AvailableBookList Collection:
AvailableBookList = Backbone.Collection.extend({
model: AvailableBook,
url: "/authors/" + this.id
})
The View part:
$(document).ready(function(){
AvailableBookListView = Backbone.View.extend({
tagName: 'section',
className: 'availablebooklist',
initialize: function() {
_.bindAll(this, 'render');
this.collection.bind('reset', this.render);
},
render: function() {
this.collection.each(function(available_book) {
var view = new AvailableBookView({
model: available_book,
});
this.$('.availablebooklist').append(view.render().el);
});
return this;
}
});
});
Problem: when i visit “http://www.backboneapp.com/authors/1″ I am getting 404 error.
In console.log it shows:
get: http://www.backboneapp.com/authors/undefined
In Rails log: parameters {id => undefined}
*Where am i going wrong? *
Any help and suggestions are highly appreciated
I’m going to assume that you didn’t mean
new AuthorListin your router, but rathernew AvailableBookList.You have two problems in your collection:
thisrefers to thewindowobject.idparameter you’re passing in the constructor is not applied to your collection instance. It works this way for views only (not for models nor collections).To solve the first problem, you can use a function to define a collection url, which would put you in the correct scope:
For the second one, you can define an
initializefunction and set theidattribute in there:For readability purposes, I would also suggest renaming
idtoauthor_id:Update
You’re also initializing your collection in the wrong way. According to the Backbone.js source, the constructor signature is
models, options: