Back to Posts

AngularJS with Rails 4.2.5

I recently wanted to play around with a few things and for that I needed a Rails app with Angular on the client side. There were two approaches that I considered:

  • Have two totally different apps, one being Rails that is gonna serve as pure API and have a NodeJS server that is gonna serve AngularJS which is gonna communicate with Rails.

  • Full blown Rails app which will serve AngularJS

Both approaches have pros and cons and I have seen production code running in both approaches. Just because I felt there is less to maintain and deploy ( from a devops perspective ) I went for the approach to have a full blown Rails app.

There are a lot resources online on how to setup rails and angular but most of which I encountered deal with Rails 3.2 or Rails 4.0. In latest stable version of Rails ( 4.2.5 ) there have been some changes to the standard gem set you would find in those tutorials so I needed to do a bit of digging but at the end I made it! :)

Setup

Before we start anything I am going to assume that you already know how to use command line, how Rails works and how Rails serves assets. Also I am going to assume you know what Bower is and how dependency management works.

First thing we need something to work with so we are going to initialize a new Rails 4.2.5 app:

$ rails new awesome_app --database=postgresql

After this command has finished executing we need to setup our database:

cd awesome_app  
bundle exec rake db:create  
bundle exec rake db:migrate  

Next we need to remove turbolinks from our app, in order to do that we need to do two steps:

  • Remove it from a Gemfile
gem 'turbolinks'  
  • Remove it from application.js
//= require turbolinks

Up until this point we were just preparing our app for AngularJS and did some initial setup work. Next we need to install gems that are gonna help us serve angular templates and install angular. Put these two gems in your Gemfile:

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

bower-rails enables us to use Bower package manager within our Rails app. It will allow us to install Angular and any other js package that we want. Its pretty cool. I know that there is a recent movement in JS community to move everything to NPM package manager but bower is still very relevant. angular-rails4-templates allows us to serve angular templates from templates directory. Most of the tutorials out there ( at least at the time of writing this post ) will tell you to install angular-rails-templates which is going to cause problems because its not compatible with new sprockets version that comes with Rails 4.2.5. Thus there was a new similar gem (angular-rails4-templates) that works with our version of Rails.

Next you need to install these new sexy gems by running:

$ bundle install

Next we need to initialize our bower file where we will manage our js dependencies by running:

$ bundle exec rails g bower_rails:initialize json

This should add Bowerfile file to the root folder of your app and you should make it look something like this:

# A sample Bowerfile
# Check out https://github.com/42dev/bower-rails#ruby-dsl-configuration for more options
# Example:
# asset 'bootstrap'


asset 'angular'  

Currently we only have angular but you can list anything you want in the future.

Now we need to run a command to install angular:

$ bundle exec rake bower:install 

This should install angular in vendor/assets/bower_components/angular. Now we need to add angular to our asset pipeline by inserting these two lines in application.js:

//= require angular
//= require angular-rails4-templates
//= require angular/app

Last require is needed to include a file that will be created later in this post to bootstrap angular.

And this should wrap up the full setup.

Testing everything out

Now that we have everything installed its time to test if Angular works as we expected, in your routes.rb file add this line:

  root 'example#home'

Then we need to create a rails controller to support this route:

$ touch app/controllers/example_controller.rb

Open up that file and it needs to look something like this:

class ExampleController < ApplicationController  
  def home
  end
end  

After this we need to crate a view for this controller and use that as our Angular app. Let's do the following:

$ mkdir app/views/example
$ touch app/views/example/home.html.erb

Then inside of that file we need to bootstrap our angular app:

<div ng-app="myApp"></div>  

Then we need to bootstrap the angular from js side of things:

$ mkdir app/assets/javascripts/angular
$ touch app/assets/javascripts/app.js

Inside of our app.js we are gonna write a few lines of code that will write to our browsers console and start our angular app:

var app = angular.module('app', ['templates']);                                                

app.config([  
  '$httpProvider', function($httpProvider) {
        return $httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content');
    }j
]);

app.run(function() {  
  return console.log('angular is working'); 
});

Now start your server with bundle exec rails s and go to the given url and look at the console and you should see an output from angular angular is working!

Yayyyy! We are finally finished up. Enjoy!
Let me know via twitter or anywhere if I missed something out or if you really liked it :)

Software engineer that loves business side of things as well. Also lifts a lot of weights.

Read Next

Review of 2015