Easily setup and use backbone.js (1.1.2) with Rails 3.1 and greater
Github master branch
Gem version : 1.1.2
Backbone version : 1.1.2
Underscore version : 1.8.2
Gem version : 0.9.10
Backbone version : 0.9.10
Underscore version : 1.4.3
These awesome people helped to keep this gem updated
This gem requires the use of rails 3.1 and greater, coffeescript and the new rails asset pipeline provided by sprockets.
This gem vendors the latest version of underscore.js and backbone.js for Rails 3.1 and greater. The files will be added to the asset pipeline and available for you to use.
In your Gemfile, add this line:
Then run the following commands:
bundle install rails g backbone:install
Layout and namespacing
rails g backbone:install will create the following directory structure under
routers/ models/ templates/ views/
It will also create a toplevel app_name.coffee file to setup namespacing and setup initial requires.
rails g backbone:model model_name [property_name:property_type[,]]
This generator creates a backbone model and collection inside
rails g backbone:router model_name [action_name[,]]
This generator creates a backbone router with corresponding views and templates for the given actions provided.
rails g backbone:scaffold model_name [property_name:property_type[,]]
This generator creates a router, views, templates, model and collection to create a simple crud single page app
Created a new rails application called
rails new blog
Edit your Gemfile and add
Install the gem and generate scaffolding.
bundle install rails g backbone:install rails g scaffold Post title:string content:string rake db:migrate rails g backbone:scaffold Post title:string content:string
You now have installed the backbone-rails gem, setup a default directory structure for your frontend backbone code. Then you generated the usual rails server side crud scaffolding and finally generated backbone.js code to provide a simple single page crud app. You have one last step:
Edit your posts index view
app/views/posts/index.html.erb with the following contents:
If you prefer haml, this is equivalent to inserting the following code into
Now start your server
rails s and browse to localhost:3000/posts
You should now have a fully functioning single page crud app for Post models.
Sample application can be found here
Overrides backbone sync function
This gem overrides the backbone sync function. Check here for details.
With Rails 4:
If you are using the default Rails 4 scaffold generators, you will need to adjust the default JSON show view (IE, 'show.json') to render the 'id' attribute.
default rails generated show.json.jbuilder
json.extract! @post, :title, :content, :created_at, :updated_at
Change it to add
id attribute as well
json.extract! @post, :id, :title, :content, :created_at, :updated_at
Without adjusting the JSON show view, you will be redirected to a "undefined" url after creating an object.