Simple Web App with RoR
Unless you have lived under a rock for the past 5 years or so, you should have already heard of Ruby on Rails. In this article, we’ll write a very simple web application to show its power and speed of development.
We’ll cover the following topics:
install the rails gem
how to start a new rails project
directory structure of a rails project
how to manage data with a database
use already available components to handle common tasks
add CRUD resources
improve the app flawlessy
The following section offers a very quick overview of the tools you need to get started with Ruby on Rails development. If you already have a working rails environment, excluding the default ruby installation that some operating systems have, then feel free to skip the steps.
If you run Linux or MacOSX on your computer, you may already have Ruby installed by default, however these kind of installations are out of date (eg: ruby 1.8.x) and gems are difficult to manage. The best way is to install it manually or just use some tool that helps to manage custom Ruby installations, even multiple versions (eg: 1.9.x and 2.0.0 releases).
Instead of repeating what others have already said, here are some useful guides:
MacOSX: Ruby on Rails development with Mac OS X Mountain Lion. Follow the steps until you reach Install SQLite3 section, we’ll see here how to install rails.
Linux: Setup Ruby On Rails on Ubuntu 13.04. Same as above, follow the steps until you reach Configuring Git.
Windows: SQLite3 Ruby 2.0 on Windows and Getting Started with Git and GitHub on Windows. I haven’t too much experience on windows, so keep the finger crossed and/or ask on the same forum thread. The Ruby community is very kind
Now, you should have all the requirements to get started.
Install Bundler gem
Bundler is a Ruby gem that helps you to manage development dependencies in a project. We’ll see how it works later, for now, just install it:
gem install bundler
Install Rails v4.0.0.rc2 gem
We’re going to use the upcoming new version of rails. It’s the 2nd Release Candidate but, according to its author, it should be stable enough.
gem install rails -v4.0.0.rc2
A Simple Web Application to Manage and Share Bookmarks
Someone says that doing it is the best way to learn, so here’s a less common tutorial app: a simple platform to manage or share bookmarks. It’s nothing fancy, but it’s enough to apply some basic concepts. Moreover, aren’t you bored of todo lists and blog engines over and over?
Create the rails app
When you install rails, it comes with a bunch of other libraries and/or command line tools. The main one is rails. For now, we’ll use it to generate the initial skeleton:
rails new bookmarks -T -d sqlite3 -B
I’ve also passed some arguments to the command:
bookmarks: is the name of our project.
-T: skip Test::Unit files. It’s not fundamental for our purpose (but they are in the everyday Ruby and Rails development), so I skipped them because testing is an argument apart and I don’t want to overcomplicate this article.
-d sqlite3: we want to use SQLite database. It fits perfectly for our purposes. Please note that, Rails has support for a wide variety of databases, even NoSQL ones. It’s also common to have different database engines based on the environment (eg: SQLite for development, MySQL or PostgreSQL for production, etc…) without code changes.
-B: don’t run bundle install, we’ll do it manually later.
Once you run the command, you should see a long list of lines that explain what is happening:
andrea@mbair ~/Works/12dos % rails new bookmarks -T -d sqlite3
andrea@mbair ~/Works/12dos % cd bookmarks
andrea@mbair ~/Works/12dos/bookmarks %
A new directory called bookmarks (or whatever project name you passed) has been created, along with a set of files and directories inside it. Enter this directory, we’ll see the important contents during the article.
A first look at Bundler and Gemfile
We mentioned Bundler as a tool to manage development dependencies in a Ruby app. It works by reading a file called Gemfile that should be present in the root directory of the app. You need this to make sure all the required gems are installed, even rails itself. Here’s a brief look at the Gemfile generated by the rails new command:
# Our rails version
gem 'rails', '4.0.0.rc2'
# Use sqlite3 as the database for Active Record
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0.rc2'
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0
# Uncomment this if you haven't a nodejs and coffeescript installed
# gem 'therubyracer', platforms: :ruby
As you can see, this is the default list of gems you need to start working on a Rails project. Of course, you’ll change it very often to add, remove or upgrade gems.
Now you can finally run bundle install on the command line.
If you use git, this is a good moment to initialize the repo and proceed with the initial commit.
Run the development server
Even if you haven’t yet wrote any line of code, you can already use the Rails development server. Run the following command: rails server or rails server -b $IP -p $PORT
then point your browser to http://localhost:3000 and you’ll get a standard welcome page. This time we’ve used rails server, another useful command offered by Rails, moreover, it works only when you run it inside a Rails project folder. We’ll see other useful commands later.
A quick introduction to MVC patterns and Rails
Rails is usually defined as an MVC framework. Basically, it means that the app behaviour is defined in this way:
Model: manages data between the rest of the application and the database. You can define how a single entity behaves, this includes data validation, before/after save hooks, etc…
Controller: this is the glue between the data managed by the Models and the rendered Views. Http requests that come to your app, are routed to a controller which usually will interact with one or more models and finally renders the ouput along with an Http response.
View: the final output for a request. It’s usually a piece of HTML, but it might also be JSON or XML. We’ll see this later.
This is, of course, an over-simplification, but it should be enough to get a vague idea of how it works. I’ll dive into some details later.
Add a Bookmark resource
The goal of our app is to manage bookmarks, right? So we’ll need to create our Bookmarkresource:
rails generate scaffold bookmark title:string url:string
route resources :bookmarks
This time, we’ve used rails generate, one of the most useful commands. In this case, we’ve generated a scaffold that creates all the necessary files and code to automatically get a full MVC stack that manages a Bookmark. In the next few paragraphs, we’ll see in detail what the above command did.
We’ve specified that a Bookmark record is made of a title and a url fields, both of type string(255 chars by default). So, the rails scaffold generator has automatically created a migrationscript to update your database schema: db/migrate/db/migrate/20130614142337_create_bookmarks.rb
class CreateBookmarks < ActiveRecord::Migration
create_table :bookmarks do |t|
Even if it’s almost easy to read, this code basically means:
create a bookmarks table on database (note the pluralized form)
it has the fields title and url of type string
also add timestmps by default (this is automatically translated to created_at andupdated_at datetime fields)
However, your database still doesn’t know about these changes to the schema, you need to run the migration task: rake db:migrate
Rake is another common and useful tool in the Ruby world. It acts like a Makefile in a Ruby fashion. Rails comes with several rake tasks ready to use (you can also create custom ones, if needed): rake -T
Try on the server
Now, the fun part. Restart your rails server with rails server and go to http://localhost:3000/bookmarks. If you followed the above example in console, you should already see the Bookmark created earlier, otherwise, you can create a new one by clicking on New bookmark link.
Try http://localhost:3000/bookmarks.json and see what you’ll get. You still haven’t wrote a single line of Ruby, and it already does a lot of things. Awesome, isn’t it?
You can even use this 'generate' method to create other models such as a user authentification. Go to the gemfile folder and put: gem 'devise', '~> 3.0.0.rc'
Then run Bundle Installl
rails generate devise:install
Generate a User model
Setup for Devise is done, but we still haven’t a User model, we need to create one: rails generate devise User
Users have many Bookmarks
Now that we have User and Bookmark, we need to associate them. In this case, it’s a one to many relationship. As a shared convention, foreign keys name are made of the model name suffixed by _id. Of course, we’ll not change the already created migrations, instead, we’re going to create a new one:
rails generate migration AddUserIdToBookmark user_id:integer
Try on the server
If you haven’t played with the web interface yet, now is a good time to do it. Here are some hints:
go to http://localhost:3000, it should redirect to http://localhost:3000/users/sign_in, the login page;
if you haven’t registered any user, then go to http://localhost:3000/users/sign_up and register a new one;
retry to go to http://localhost:3000/ again, it will work as well as going tohttp://localhost:3000/bookmarks because they’re the same action;
create some bookmarks from http://localhost:3000/bookmarks/new.