Post navigation

2: Creating the base rails backend

In this portion of the Rails4 and AngularJS tutorial we build the base of the rails backend. We’ll come back later and add Devise and CanCan to it, for now we’re just focusing on having an application that runs and serves json, at the end of this segment you should end up with a Rails server that is providing clubs.json and teams.json, ready to have the Angular frontend added.

If you’re interested in the rest of this tutorial, you can visit the index page, or you can hit the tutorials menu above and look at the rails 4 tutorial category. If you haven’t yet installed Rails 4 you may want to look at the previous page on installation, and if you’re fine with the Rails portion, you may want to move onto the next page that starts the AngularJS install. Finally, the code for the position at the end of this section of the tutorial can be found on github:PaulL:tutorial_1_and_2.

In your browser, the aim of this section of the tutorial is to get something like the screenshot below:

The base application has two entities, loosely based around a sports league. It has a set of clubs, with each club having multiple teams. In later sections of the tutorial we’ll set it up so that only some users can edit some clubs, but for now we’re completely ignoring the security.

If you didn’t already do so in the previous page, create a new rails application:

rails new league-tutorial-rails4

Run the installer to make sure everything is installed:

bundle install

Initialise your git project if you want to use git (I won’t note where you should be committing along the way, but it’s good practice to do regular commits to allow you to get back to what you had before):

git init --shared=group

Start off by creating the club entity. A club is very simple – it has a name, a contact_officer, and a date_created:

You’ll notice the intercept_html_requests method isn’t here, we don’t want to keep duplicating it so we’re moving it into application_controller.rb, so also take out of the clubs_controller.rb. The application_controller should look like:

class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
# if someone asks for html, redirect them to the home page, we only serve json
def intercept_html_requests
redirect_to('/') if request.format == Mime::HTML
end
end

You’ll notice that we didn’t make teams a nested route of clubs – we’re assuming that teams can either be inside a club, or can exist outside a club. So we’re going to leave the club_id as optional on the team, and create the relationship within our angular app later.

This post will be updated for CSRF and JSONP vulnerabilities once we have some AngularJS working against it and can verify whether that all works or not.