Angular with Rails, Part I: Setting Up a Project

When it comes to Angular and Rails, there are many ways to set up a project. However when starting out, all these options can be a tad overwhelming…

Over the last few months, I’ve been focusing on project set-ups and have come to find a few favorites. In this post, I’ll illustrate one way to use Rails with Angular (see Github links with the example code below).

Create a New Rails App

To get started lets create a new rails app.

In this app, I chose not to use turbolinks. It’s possible to use Angular with Rails and turbolinks, but the Angular app bootstrap process is more complex. I find that turbolinks and Angular serve the same purpose, which is to make the app respond faster. Adding turbolinks, in addition to Angular, adds a lot of complexity and not much benefit.

Remove Turbolinks

Removing turbolinks requires removing it from the Gemfile.

Remove the require from app/assets/javascripts/application.js

Add AngularJS to the Asset Pipeline

In order to get Angular to work with the Rails asset pipeline we need to add to the Gemfile:

Next, we can install these gems into our bundle.

We added bower so that we can install the AngularJS dependency.

When adding Angular to bower.json, I prefer to specify the most recent version rather than going with the “latest”. This avoids having your app randomly break when a new version is released and your bower installs again.

Now that bower.json is setup with the right dependencies, let’s install them:

Organize the Angular App

At this point we’ll create the following folder structure in app/assets/javascript/angular-app:

This structure is only a convention and is not enforced by Angular (unlike file naming and organization in Rails). This project structure allows for a single web app to be easily composed of multiple smaller Angular modules rather than one giant Angular app for the whole site.

In app/assets/javascripts/application.js add Angular, the template helper, and the Angular app file structure. That file should now read like this:

Bootstrap the Angular App

Next, we’ll setup the Angular app bootstrapping. Create app/assets/javascripts/angular-app/

Then, we’ll create an Angular module at app/assets/javascripts/angular-app/modules/

Following the Angular module, we’ll create an Angular controller for this app at app/assets/javascripts/angular-app/controllers/

Now we need to add a route to Rails to pass control over to Angular. In config/routes.rb:

Next, we’ll generate the Rails controller to respond to that route:

In app/controllers/example_controller.rb:

In the view we need to specify which Angular app, and which Angular controller will drive this page.

In app/views/example/index.html.erb:

To view the app, start your Rails server and visit http://localhost:3000/example

You can find the code generated here