Angular with Rails, Part I: Setting Up a Project

Posted by Mobomo on September 25, 2014

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.

1

gem install rails-v4.1rails newangular_example

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.

1

gem'turbolinks'

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

1

//= require turbolinks

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:

1

gem'angular-rails-templates'gem'bower-rails'

Next, we can install these gems into our bundle.

1

bundle install

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

1

railsgbower_rails:initialize json

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:

1

bundle exec rake bower:install

Organize the Angular App

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

1

templates/modules/filters/directives/models/services/controllers/

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: