Angular & Rails: Part 2

The example application mentioned in this post can be found here: https://justcheckin.herokuapp.com

As a follow up to my previous post talking about the benefits of using AngularJS and Ruby on Rails together on your next project. I’d like to go through a tutorial of how to build a simple application using both technologies. In this tutorial, I’ll go over getting the backend (Using Rails) and how to get it up and running.

Prerequisites

This will require a basic understanding of Ruby on Rails. You will also need to have Ruby 2.2.1, Rails 4.2.1, and PostgreSQL installed on your local computer. Also, many of the examples are going to be described using a UNIX computer, which will apply for Mac and Linux systems (May require some workarounds for Windows users).

Create the App

1. Let’s create a new Rails application. Using your terminal, navigate to your directory that you would like too place this new app directory and run the following command

rails new checkin

This will create a base Rails application with the basic configuration.

2. We will need to create a new controller “Checkins” and a new model “Checkin” for our basic application to work. We will use rails generator to create them for us. Navigate to the newly application directory and run the following commands in your terminal

rails g controller Checkins

rails g model Checkin browser:string mobile:boolean os:string

The arguments for the model generator will go ahead and create the necessary model/database columns to interact with when we create the database.

Create / Setup the Database

1. Now that we have defined the schema of the model, it may be beneficial to get our database up and running for development using this new schema. Since we are using PostgreSQL as our database, we will need to install the necessary files for rails to use it. At the root of your app’s directory, you will find Gemfile. Open the gemfile, and add the following line

[sourcecode language=”ruby”]
gem ‘pg’
[/sourcecode]

2. Within your terminal, navigate to your app’s directory and run the following command to download the necessary dependencies.

bundle install

3. Now back in your editor, go to your app/config directory and open the database.yml file. You will want to set it up to look like the below code, but will need to replace the [USERNAME] and [PASSWORD] fields with Postgres users that have the necessary permissions to the database.

[sourcecode language=”ruby”]
default: &default
adapter: postgresql
encoding: unicode
template: template0
pool: 5

dev&test: &devtest
<<: *default
host: localhost
port: 5432

development:
<<: *devtest
database: checkin_development
username: [USERNAME]
password: [PASSWORD]

test:
<<: *devtest
database: checkin_test
username: [USERNAME]
password: [PASSWORD]

production:
<<: *default
database: checkin_production
url: <%= ENV["db_url"] %>
username: <%= ENV["db_username"] %>
password: <%= ENV["db_password"] %>
[/sourcecode]

4. Then if all is set up correctly, you should be able to run the following commands in your terminal to set up the databases.

rake db:create

rake db:migrate

Create will actually create the databases for the first time, while migrate will create the necessary tables/columns based on your models & migrations.

Let’s Start Coding

1. Open up your text editor and navigate to the app/controllers directory and open up the checkins_controller.rb file. We will need to create 2 new methods to interact with our application. One method “index” will be used to return us the data we need to display to the outside world. The other method “checkin” will be used to record new information for the app. We also need to define our protected parameters here. Per Rails 4, protected parameters allow you indicate what parameters you will allow the external application to pass through to the controller (helping you prevent any malicious parameters). Add the following code to this controller:

[sourcecode language=”ruby”]
class CheckinsController < ApplicationController
protect_from_forgery with: :null_session

def index
end

def checkin
end

private

def checkin_params
params.require(:checkin).permit(:browser, :mobile, :os)
end
end
[/sourcecode]

2. Now that we have the skeleton for the controller set up, we will need to create a model method to retrieve the records we need to display to an end user. So navigate to your app/models directory and open the checkin.rb file. Since we don’t need anything to complicated, we will just create a named scope. A named scope is a class method that allows us to configure how we want the data to be extracted from the database. Let’s create one that pulls the last 25 records sorted by most recent.

[sourcecode language=”ruby”]
class Checkin < ActiveRecord::Base
scope :recent_checkins, -> { order(‘checkins.created_at DESC’).limit(25) }

end
[/sourcecode]

3. Now back in our controller, let’s update our index method to use this new method on the Checkin model to retrieve this data. The respond_to block is set up so that it’ll render the @checkins object in response to json requests.

[sourcecode language=”ruby”]
def index
@checkins = Checkin.recent_checkins
respond_to do |format|
format.json { render json: @checkins.to_json, status: 200}
end
end
[/sourcecode]

4. Additionally, let’s update our checkin method so that it will create a checkin in the database when called. The code below will create a new instance of Checkin with the parameters passed in (The ones that we approved at the beginning). Then, it will try to save the instance in the database using ActiveRecord. If successful, it will return the object in JSON or if not then it’ll render the errors in JSON.

[sourcecode language=”ruby”]
def checkin
@checkin = Checkin.new(checkin_params)

respond_to do |format|
if @checkin.save
format.json { render json: @checkin.to_json, status: 200}
else
format.json { render json: @checkin.errors.to_json, status: :unproccessable_entity}
end
end
end
[/sourcecode]

5. So now that we have the controller methods set up, we will need to allow access to these methods via routes. Navigate to your app/configs directory and open the routes.rb file. We will add a few lines to enable GET and POST requests to the necessary endpoints in the controller.

[sourcecode language=”ruby”]
Rails.application.routes.draw do
scope :api, defaults: {format: :json} do
get ‘/recent_checkins’ => "checkins#index", as: "checkins"
post ‘/checkin’ => "checkins#checkin", as: "checkin"
end
end
[/sourcecode]

6. Now you should be able to interact with your application using RESTful requests. If you have an application like postman, you can create checkins by posting to “/checkin” with the following parameters (browser, os, and mobile). You can receive a list of the last 25 of them by just navigating to “/checkins”.

Now that we have a working backend, the next Blog post for this series will go over creating the AngularJS client application that will interact with our backend.