Ruby on Rails - Quick Guide


Ruby on Rails - Introduction

What is Ruby?

Before we ride on Rails, let us recapitulate a few points of Ruby, which is the base of Rails.

Ruby is the successful combination of:

  • Smalltalk's conceptual elegance,
  • Python's ease of use and learning, and
  • Perl's pragmatism.

Ruby is

  • A high level programming language
  • Interpreted like Perl, Python, Tcl/TK.
  • Object-oriented like Smalltalk, Eiffel, Ada, Java.

Why Ruby?

Ruby originated in Japan and now it is gaining popularity in US and Europe as well. The following factors contribute towards its popularity:

  • Easy to learn
  • Open source (very liberal license)
  • Rich libraries
  • Very easy to extend
  • Truly object-oriented
  • Less coding with fewer bugs
  • Helpful community

Although we have many reasons to use Ruby, there are a few drawbacks as well that you may have to consider before implementing Ruby:

  • Performance Issues - Although it rivals Perl and Python, it is still an interpreted language and we cannot compare it with high-level programming languages like C or C++.

  • Threading model – Ruby does not use native threads. Ruby threads are simulated in the VM rather than running as native OS threads.

Sample Ruby Code

Here is a sample Ruby code to print "Hello Ruby"

# The Hello Class
class Hello
   def initialize( name )
      @name = name.capitalize

   def salute
      puts "Hello #{@name}!"

# Create a new object
h ="Ruby")

# Output "Hello Ruby!"
Hello Ruby!

Embedded Ruby

Ruby provides a program called ERb (Embedded Ruby), written by Seki Masatoshi. ERb allows you to put Ruby codes inside an HTML file. ERb reads along, word for word, and then at a certain point, when it encounters a Ruby code embedded in the document, it starts executing the Ruby code.

You need to know only two things to prepare an ERb document:

  • If you want some Ruby code executed, enclose it between <% and %>.

  • If you want the result of the code execution to be printed out, as a part of the output, enclose the code between <%= and %>.

Here's an example. Save the code in erbdemo.rb file. Note that a Ruby file will have an extension .rb:

<% page_title = "Demonstration of ERb" %>
<% salutation = "Dear programmer," %>

      <title><%= page_title %></title>
      <p><%= salutation %></p>
      <p>This is an example of how ERb fills out a template.</p>

Now, run the program using the command-line utility erb.

c:\ruby\>erb erbdemo.rb

This will produce the following result:


      <title>Demonstration of ERb</title>
      <p>Dear programmer,</p>
      <p>This is an example  of how ERb fills out a template.</p>

What is Rails?

  • An extremely productive web-application framework.

  • Written in Ruby by David Heinemeier Hansson.

  • You could develop a web application at least ten times faster with Rails than you could with a typical Java framework.

  • An open source Ruby framework for developing database-backed web applications.

  • Your code and database schema are the configuration!

  • No compilation phase required.

Full Stack Framework

  • Includes everything needed to create a database-driven web application, using the Model-View-Controller pattern.

  • Being a full-stack framework means all the layers are built to work seamlessly together with less code.

  • Requires fewer lines of code than other frameworks.

Convention over Configuration

  • Rails shuns configuration files in favor of conventions, reflection, and dynamic run-time extensions.

  • Your application code and your running database already contain everything that Rails needs to know!

Rails Strengths

Rails is packed with features that make you more productive, with many of the following features building on one other.

Metaprogramming - Other frameworks use extensive code generation from scratch. Metaprogramming techniques use programs to write programs. Ruby is one of the best languages for metaprogramming, and Rails uses this capability well. Rails also uses code generation but relies much more on metaprogramming for the heavy lifting.

Active Record - Rails introduces the Active Record framework, which saves objects to the database. The Rails version of the Active Record discovers the columns in a database schema and automatically attaches them to your domain objects using metaprogramming.

Convention over configuration - Most web development frameworks for .NET or Java force you to write pages of configuration code. If you follow the suggested naming conventions, Rails doesn't need much configuration.

Scaffolding - You often create temporary code in the early stages of development to help get an application up quickly and see how major components work together. Rails automatically creates much of the scaffolding you'll need.

Built-in testing - Rails creates simple automated tests you can then extend. Rails also provides supporting code called harnesses and fixtures that make test cases easier to write and run. Ruby can then execute all your automated tests with the rake utility.

Three environments - Rails gives you three default environments: development, testing, and production. Each behaves slightly differently, making your entire software development cycle easier. For example, Rails creates a fresh copy of the Test database for each test run.

Ruby on Rails - Installation

To develop a web application using Ruby on Rails Framework, you need to install the following software:

  • Ruby
  • The Rails framework
  • A Web Server
  • A Database System

We assume that you already have installed a Web Server and a Database System on your computer. You can always use the WEBrick Web Server, which comes with Ruby. Most sites, however, use Apache or lightTPD in production.

Rails works with many database systems, including MySQL, PostgreSQL, SQLite, Oracle, DB2 and SQL Server. Please refer to a corresponding Database System Setup manual to setup your database.

Let's look at the installation instructions for Rails on Windows, Mac OS X, and Linux.

Rails Installation on Windows

  • First, let's check to see if you already have Ruby installed. Bring up a command prompt and type ruby -v. If Ruby responds, and if it shows a version number at or above 1.8.2, then type gem --version. If you don't get an error, skip to step 3. Otherwise, we'll install a fresh Ruby.

  • If Ruby is not installed, then download an installation package from Follow the download link, and run the resulting installer. This is an exe like ruby186-25.exe and will be installed in a single click. You may as well install everything . It's a very small package, and you'll get RubyGems as well along with this package. Please check the Release Notes for more detail.

  • With RubyGems loaded, you can install all of Rails and its dependencies through the command line:

C:\> gem install rails --include-dependencies

NOTE: The above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies.

Congratulations! You are now on Rails over Windows.

Rails Installation on Mac OS X

  • First, let's check to see if you already have Ruby installed. Bring up a command prompt and type ruby -v. If Ruby responds, and if it shows a version number at or above 1.8.2, then skip to step 3. Otherwise, we'll install a fresh Ruby. To install a fresh copy of Ruby, the UNIX instructions that follow should help.

  • Next you have to install RubyGems. Go to and follow the download link. OS X will typically unpack the archive file for you, so all you have to do is navigate to the downloaded directory and (in the Terminal application) type.

tp> tar xzf rubygems-x.y.z.tar.gz
tp> cd rubygems-x.y.z
rubygems-x.y.z> sudo ruby setup.rb
  • Now use RubyGems to install Rails. Still in the Terminal application, issue the following command.

tp> sudo gem install rails --include-dependencies

NOTE: The above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies.

Congratulations! You are now on Rails over Mac OS X.

Rails Installation on Linux

  • First, let's check to see if you already have Ruby installed. Bring up a command prompt and type ruby -v. If Ruby responds, and if it shows a version number at or above 1.8.2, then skip to step 3. Otherwise, we'll install a fresh Ruby.

  • Download ruby-x.y.z.tar.gz from

  • Extract files from the distribution, and enter the top-level directory.

  • Do the usual open-source build as follows:

tp> tar -xzf ruby-x.y.z.tar.gz
tp> cd ruby-x.y.z

ruby-x.y.z> ./configure
ruby-x.y.z> make
ruby-x.y.z> make test
ruby-x.y.z> make install
  • Install RubyGems. Go to, and follow the download link. Once you have the file locally, enter the following in your shell window.

tp> tar -xzf rubygems-0.8.10.tar.gz
tp> cd rubygems-0.8.10
rubygems-0.8.10> ruby setup.rb
  • Now use RubyGems to install Rails. Still in the shell, issue the following command.

tp> gem install rails --include-dependencies

NOTE: The above command may take some time to install all dependencies. Make sure you are connected to the internet while installing gems dependencies.

Congratulations! You are now on Rails over Linux.

Keeping Rails Up-to-Date

Assuming you have installed Rails using RubyGems, keeping it up-to-date is relatively easy. Issue the following command:

tp> gem update rails

This will automatically update your Rails installation. The next time you restart your application, it will pick up this latest version of Rails. While giving this command, make sure you are connected to the internet.

Installation Verification

You can verify if everything is setup according to your requirements or not. Use the following command to create a demo project.

tp> rails demo

This will generate a demo rail project, we will discuss about it later. Currently we have to check if the environment is setup or not. Next, use the following command to run WEBrick web server on your machine.

tp> cd demo
tp> ruby script/server
⇒ Rails application started on
⇒ Ctrl-C to shutdown server; call with --help for options
[2007-02-26 09:16:43] INFO WEBrick 1.3.1
[2007-02-26 09:16:43] INFO ruby 1.8.2 (2004-08-24)...
[2007-02-26 09:16:43] INFO WEBrick::HTTPServer-start:pid=2836...

Now open your browser and type the following address text box.


It should display a message, something like, "Welcome aboard" or "Congratulations".

Ruby on Rails - Framework

A framework is a program, set of programs, and/or code library that writes most of your application for you. When you use a framework, your job is to write the parts of the application that make it do the specific things you want.

When you set out to write a Rails application, leaving aside the configuration and other housekeeping chores, you have to perform three primary tasks:

  • Describe and model your application's domain - The domain is the universe of your application. The domain may be a music store, a university, a dating service, an address book, or a hardware inventory. So here you have to figure out what's in it, what entities exist in this universe and how the items in it relate to each other. This is equivalent to modeling a database structure to keep the entities and their relationship.

  • Specify what can happen in this domain - The domain model is static; you have to make it dynamic. Addresses can be added to an address book. Musical scores can be purchased from music stores. Users can log in to a dating service. Students can register for classes at a university. You need to identify all the possible scenarios or actions that the elements of your domain can participate in.

  • Choose and design the publicly available views of the domain - At this point, you can start thinking in Web-browser terms. Once you've decided that your domain has students, and that they can register for classes, you can envision a welcome page, a registration page, and a confirmation page, etc. Each of these pages, or views, shows the user how things stand at a certain point.

Based on the above three tasks, Ruby on Rails deals with a Model/View/Controller (MVC) framework.

Ruby on Rails MVC Framework

The Model View Controller principle divides the work of an application into three separate but closely cooperative subsystems.

Model (ActiveRecord )

It maintains the relationship between the objects and the database and handles validation, association, transactions, and more.

This subsystem is implemented in ActiveRecord library, which provides an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.

View ( ActionView )

It is a presentation of data in a particular format, triggered by a controller's decision to present the data. They are script-based template systems like JSP, ASP, PHP, and very easy to integrate with AJAX technology.

This subsystem is implemented in ActionView library, which is an Embedded Ruby (ERb) based system for defining presentation templates for data presentation. Every Web connection to a Rails application results in the displaying of a view.

Controller ( ActionController )

The facility within the application that directs traffic, on the one hand, querying the models for specific data, and on the other hand, organizing that data (searching, sorting, messaging it) into a form that fits the needs of a given view.

This subsystem is implemented in ActionController, which is a data broker sitting between ActiveRecord (the database interface) and ActionView (the presentation engine).

Pictorial Representation of MVC Framework

Given below is a pictorial representation of Ruby on Rails Framework:

Rails Framework

Directory Representation of MVC Framework

Assuming a standard, default installation over Linux, you can find them like this:

tp> cd /usr/local/lib/ruby/gems/1.8/gems
tp> ls

You will see subdirectories including (but not limited to) the following:

  • actionpack-x.y.z
  • activerecord-x.y.z
  • rails-x.y.z

Over a windows installation, you can find them like this:

C:\>cd ruby\lib\ruby\gems\1.8\gems

You will see subdirectories including (but not limited to) the following:

  • actionpack-x.y.z
  • activerecord-x.y.z
  • rails-x.y.z

ActionView and ActionController are bundled together under ActionPack.

ActiveRecord provides a range of programming techniques and shortcuts for manipulating data from an SQL database. ActionController and ActionView provides facilities for manipulating and displaying that data. Rails ties it all together.

Ruby on Rails - Directory Structure

When you use the Rails helper script to create your application, it creates the entire directory structure for the application. Rails knows where to find things it needs within this structure, so you don't have to provide any input.

Here is a top-level view of a directory tree created by the helper script at the time of application creation. Except for minor changes between releases, every Rails project will have the same structure, with the same naming conventions. This consistency gives you a tremendous advantage; you can quickly move between Rails projects without relearning the project's organization.

To understand this directory structure, let's use the demo application created in the Installation chapter. It can be created using a simple helper command C:\ruby\> rails demo.

Now, go into the demo application root directory as follows:

C:\ruby\> cd demo
C:\ruby\demo> dir

You will find a directory structure as follows:


Now let's explain the purpose of each directory

  • app - It organizes your application components. It's got subdirectories that hold the view (views and helpers), controller (controllers), and the backend business logic (models).

  • app/controllers - The controllers subdirectory is where Rails looks to find the controller classes. A controller handles a web request from the user.

  • app/helpers - The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered.

  • app/models - The models subdirectory holds the classes that model and wrap the data stored in our application's database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple!

  • app/view - The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser.

  • app/view/layouts - Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the <tt>layout:default</tt> and create a file named default.html.erb. Inside default.html.erb, call <% yield %> to render the view using this layout.

  • components - This directory holds components, tiny self-contained applications that bundle model, view, and controller.

  • config - This directory contains the small amount of configuration code that your application will need, including your database configuration (in database.yml), your Rails environment structure (environment.rb), and routing of incoming web requests (routes.rb). You can also tailor the behavior of the three Rails environments for test, development, and deployment with files found in the environments directory.

  • db - Usually, your Rails application will have model objects that access relational database tables. You can manage the relational database with scripts you create and place in this directory.

  • doc - Ruby has a framework, called RubyDoc, that can automatically generate documentation for code you create. You can assist RubyDoc with comments in your code. This directory holds all the RubyDoc-generated Rails and application documentation.

  • lib - You'll put libraries here, unless they explicitly belong elsewhere (such as vendor libraries).

  • log - Error logs go here. Rails creates scripts that help you manage various error logs. You'll find separate logs for the server (server.log) and each Rails environment (development.log, test.log, and production.log).

  • public - Like the public directory for a web server, this directory has web files that don't change, such a s JavaScript files (public/javascripts), graphics (public/images), stylesheets (public/stylesheets), and HTML files (public).

  • script - This directory holds scripts to launch and manage the various tools that you'll use with Rails. For example, there are scripts to generate code (generate) and launch the web server (server).

  • test - The tests you write and those that Rails creates for you, all goes here. You'll see a subdirectory for mocks (mocks), unit tests (unit), fixtures (fixtures), and functional tests (functional).

  • tmp - Rails uses this directory to hold temporary files for intermediate processing.

  • vendor - Libraries provided by third-party vendors (such as security libraries or database utilities beyond the basic Rails distribution) go here.

Apart from these directories, there will be two files available in demo directory.

  • README - This file contains a basic detail about Rail Application and description of the directory structure explained above.

  • Rakefile - This file is similar to Unix Makefile, which helps with building, packaging and testing the Rails code. This will be used by rake utility supplied along with the Ruby installation.

Ruby on Rails - Examples

Subsequent chapters are based on the example given in this chapter. In this chapter, we will create a simple but operational online library system for holding and managing the books.

This application has a basic architecture and will be built using two ActiveRecord models to describe the types of data that is stored:

  • Books, which describes an actual listing.
  • Subject, which is used to group books together.

Workflow for Creating Rails Applications

A recommended workflow for creating Rails Application is as follows:

  • Use the rails command to create the basic skeleton of the application.

  • Create a database on the MySQL server to hold your data.

  • Configure the application to know where your database is located and the login credentials for it.

  • Create Rails Active Records (Models), because they are the business objects you'll be working with in your controllers.

  • Generate Migrations that simplify the creating and maintaining of database tables and columns.

  • Write Controller Code to put a life in your application.

  • Create Views to present your data through User Interface.

So, let us start with creating our library application.

Creating an Empty Rails Web Application

Rails is both a runtime web application framework and a set of helper scripts that automate many of the things you do when developing a web application. In this step, we will use one such helper script to create the entire directory structure and the initial set of files to start our Library System application.

  • Go into ruby installation directory to create your application.
  • Run the following command to create a skeleton for library application.
C:\ruby> rails library

This will create a subdirectory for the library application containing a complete directory tree of folders and files for an empty Rails application. Check a complete directory structure of the application. Check Rails Directory Structure for more detail.

Most of our development work will be creating and editing files in the library/app subdirectories. Here's a quick rundown of how to use them:

  • The controllers subdirectory is where Rails looks to find controller classes. A controller handles a web request from the user.

  • The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser.

  • The models subdirectory holds the classes that model and wrap the data stored in our application's database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple.

  • The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered.

Starting Web Server

Rails web application can run under virtually any web server, but the most convenient way to develop a Rails web application is to use the built-in WEBrick web server. Let's start this web server and then browse to our empty library application:

This server will be started from the application directory as follows. It runs on port number 3000.

C:\> cd ruby\library 
C:\ruby\library\> ruby script/server

This will start your WEBrick web server.

Now open your browser and browse to If everything is gone fine, then you should see a greeting message from WEBrick, otherwise there is something wrong with your setting.

What is next?

The next chapter explains how to create databases for your application and what is the configuration required to access these created databases.

Further, we will see what Rails Migration is and how it is used to maintain database tables.

Rails - Database Setup

Before starting with this chapter, make sure your database server is up and running. Ruby on Rails recommends to create three databases - a database each for development, testing, and production environment. According to convention, their names should be:

  • library_development
  • library_production
  • library_test

You should initialize all three of them and create a user and password for them with full read and write privileges. We are using the root user ID for our application. In MySQL, a console session in which you do this looks something like:

mysql> create database library_development;
Query OK, 1 row affected (0.01 sec)

mysql> grant all privileges on library_development.*
to 'root'@'localhost' identified by 'password';
Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

You can do the same thing for two more databases library_production and library_test.

Configuring database.yml

At this point, you need to let Rails know about the user name and password for the databases. You do this in the file database.yml, available in the C:\ruby\library\config subdirectory of Rails Application you created. This file has live configuration sections for MySQL databases. In each of the sections you use, you need to change the username and password lines to reflect the permissions on the databases you've created.

When you finish, it should look something like:

   adapter: mysql
   database: library_development
   username: root
   password: [password]
   host: localhost
   adapter: mysql
   database: library_test
   username: root
   password: [password]
   host: localhost
   adapter: mysql
   database: library_production
   username: root
   password: [password]
   host: localhost

NOTE: You can use similar setting for other databases if you are using any other database except MySQL.

What is Next?

The next two chapters explain how to model your database tables and how to manage those using Rails Migrations.

Rails Active Records - Models

Rails Active Record is the Object/Relational Mapping (ORM) layer supplied with Rails. It closely follows the standard ORM model, which is as follows:

  • tables map to classes,
  • rows map to objects and
  • columns map to object attributes.

Rails Active Records provide an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.

Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. This strategy allows simple designs and straight forward mappings between database tables and application objects.

Translating a Domain Model into SQL

Translating a domain model into SQL is generally straight forward, as long as you remember that you have to write Rails-friendly SQL. In practical terms, you have to follow certain rules:

  • Each entity (such as book) gets a table in the database named after it, but in the plural (books).

  • Each such entity-matching table has a field called id, which contains a unique integer for each record inserted into the table.

  • Given entity x and entity y, if entity y belongs to entity x, then table y has a field called x_id.

  • The bulk of the fields in any table store the values for that entity's simple properties (anything that's a number or a string).

Creating Active Record Files

To create the Active Record files for our entities for library application, introduced in the previous chapter, issue the following command from the top level of the application directory.

C:\ruby\library\> ruby script/generate model Book
C:\ruby\library\> ruby script/generate model Subject

You're telling the generator to create models called Book and Subject to store instances of books and subjects. Notice that you are capitalizing Book and Subject and using the singular form. This is a Rails paradigm that you should follow each time you create a model.

When you use the generate tool, Rails creates the actual model file that holds all the methods unique to the model and the business rules you define, a unit test file for performing test-driven development, a sample data file (called fixtures) to use with the unit tests, and a Rails migration that makes creating database tables and columns easy.

Apart from creating many other files and directories, this will create files named book.rb and subject.rb containing a skeleton definition in the app/models directory.

Content available in book.rb:

class Book < ActiveRecord::Base

Content available in subject.rb:

class Subject < ActiveRecord::Base

Creating Associations between Models

When you have more than one model in your rails application, you would need to create connection between those models. You can do this via associations. Active Record supports three types of associations:

  • one-to-one - A one-to-one relationship exists when one item has exactly one of another item. For example, a person has exactly one birthday or a dog has exactly one owner.

  • one-to-many - A one-to-many relationship exists when a single object can be a member of many other objects. For instance, one subject can have many books.

  • many-to-many - A many-to-many relationship exists when the first object is related to one or more of a second object, and the second object is related to one or many of the first object.

You indicate these associations by adding declarations to your models: has_one, has_many, belongs_to, and has_and_belongs_to_many.

Now, you need to tell Rails what relationships you want to establish within the library data system. To do so, modify book.rb and subject.rb to look like this:

class Book < ActiveRecord::Base
   belongs_to :subject

We have used a singular subject in the above example, because one Book can belong to a single Subject.

class Subject < ActiveRecord::Base
   has_many :books

We have used plural books here, because one subject can have multiple books.

Implementing Validations

The implementation of validations is done in a Rails model. The data you are entering into the database is defined in the actual Rails model, so it only makes sense to define what valid data entails in the same location.

Open book.rb and put the following validations:

class Book < ActiveRecord::Base
   belongs_to :subject
   validates_presence_of :title
   validates_numericality_of :price, :message=>"Error Message"
  • validates_presence_of - protects "NOT NULL" fields against missing user input.

  • validates_numericality_of - prevents the user, entering non numeric data.

Besides the validations mentioned above, there are other common validations. Check Rails Quick Guide.

What is Next?

In the next chapter, we will learn Rails Migration, which allows you to use Ruby to define changes to your database schema, making it possible to use a version control system to keep things synchronized with the actual code.

Rails - Migrations

Rails Migration allows you to use Ruby to define changes to your database schema, making it possible to use a version control system to keep things synchronized with the actual code.

This has many uses, including:

  • Teams of developers - If one person makes a schema change, the other developers just need to update, and run "rake migrate".

  • Production servers - Run "rake migrate" when you roll out a new release to bring the database up to date as well.

  • Multiple machines - If you develop on both a desktop and a laptop, or in more than one location, migrations can help you keep them all synchronized.

What Can Rails Migration Do?

  • create_table(name, options)
  • drop_table(name)
  • rename_table(old_name, new_name)
  • add_column(table_name, column_name, type, options)
  • rename_column(table_name, column_name, new_column_name)
  • change_column(table_name, column_name, type, options)
  • remove_column(table_name, column_name)
  • add_index(table_name, column_name, index_type)
  • remove_index(table_name, column_name)

Migrations support all the basic data types: string, text, integer, float, datetime, timestamp, time, date, binary and Boolean:

  • string - for small data types such as a title.

  • text - for longer pieces of textual data, such as the description.

  • integer - for whole numbers.

  • float - for decimals.

  • datetime and timestamp - store the date and time into a column.

  • date and time - store either the date only or time only.

  • binary - for storing data such as images, audio, or movies.

  • Boolean - for storing true or false values.

Valid column options are:

  • limit ( :limit => “50” )

  • default (:default => “blah” )

  • null (:null => false implies NOT NULL)

NOTE: The activities done by Rails Migration can be done using any front-end GUI or directly on SQL prompt, but Rails Migration makes all those activities very easy.

See the Rails API for details on these.

Create The Migrations

Here is the generic syntax for creating a migration:

C:\ruby\application> ruby script/generate migration table_name

This will create the file db/migrate/001_table_name.rb. A migration file contains the basic Ruby syntax that describes the data structure of a database table.

NOTE: Before running the migration generator, it is recommended to clean the existing migrations generated by model generators.

We will create two migrations corresponding to our three tables: books and subjects.

C:\ruby> cd library
C:\ruby\library> ruby script/generate migration books
C:\ruby\library> ruby script/generate migration subjects

Notice that you are using lower case for book and subject and plural form while creating migrations. This is a Rails paradigm that you should follow each time you create a Migration.

Edit the Code

Go to db/migrate subdirectory of your application and edit each file one by one using any simple text editor.

Modify 001_books.rb as follows:

The ID column will be created automatically, so don't do it here as well.

class Books < ActiveRecord::Migration
   def self.up
      create_table :books do |t|
         t.column :title, :string, :limit => 32, :null => false
         t.column :price, :float
         t.column :subject_id, :integer
         t.column :description, :text
         t.column :created_at, :timestamp

   def self.down
      drop_table :books

The method self.up is used when migrating to a new version, self.down is used to roll back any changes if needed. At this moment, the above script will be used to create books table.

Modify 002_subjects.rb as follows:

class Subjects < ActiveRecord::Migration
   def self.up
      create_table :subjects do |t|
         t.column :name, :string
      Subject.create :name ⇒ "Physics"
      Subject.create :name ⇒ "Mathematics"
      Subject.create :name ⇒ "Chemistry"
      Subject.create :name ⇒ "Psychology"
      Subject.create :name ⇒ "Geography"

   def self.down
      drop_table :subjects

The Above script will be used to create subjects table and will create five records in the subjects table.

Run The Migration

Now that you have created all the required migration files. It is time to execute them against the database. To do this, go to a command prompt and go to the library directory in which the application is located, and then type rake migrate as follows:

C:\ruby\library> rake db:migrate

This will create a "schema_info" table if it doesn't exist, which tracks the current version of the database - each new migration will be a new version, and any new migrations will be run until your database is at the current version.

Rake is a Ruby build program similar to Unix make program that Rails takes advantage of, to simplify the execution of complex tasks such as updating a database's structure etc.

Running Migrations for Production and Test Databases

If you would like to specify what Rails environment to use for the migration, use the RAILS_ENV shell variable.

For example:

C:\ruby\library> set RAILS_ENV=production
C:\ruby\library> rake db:migrate
C:\ruby\library> set RAILS_ENV=test
C:\ruby\library> rake db:migrate
C:\ruby\library> set RAILS_ENV=development
C:\ruby\library> rake db:migrate

NOTE: In Unix, use "export RAILS_ENV=production" instead of set command.

What is Next?

Now we have our database and the required tables available. In the two subsequent chapters, we will explore two important components called Controller (ActionController) and View (ActionView).

  • Creating Controllers (Action Controller).
  • Creating Views (Action View).

Rails Controller - ActionController

The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services.

  • It is responsible for routing external requests to internal actions. It handles people-friendly URLs extremely well.

  • It manages caching, which can give applications orders-of-magnitude performance boosts.

  • It manages helper modules, which extend the capabilities of the view templates without bulking up their code.

  • It manages sessions, giving users the impression of an ongoing interaction with our applications.

The process for creating a controller is very easy, and it's similar to the process we've already used for creating a model. We will create just one controller here:

C:\ruby\library\> ruby script/generate controller Book

Notice that you are capitalizing Book and using the singular form. This is a Rails paradigm that you should follow each time you create a controller.

This command accomplishes several tasks, of which the following are relevant here:

  • It creates a file called app/controllers/book_controller.rb

If you look at book_controller.rb, you will find it as follows:

class BookController < ApplicationController

Controller classes inherit from ApplicationController, which is the other file in the controllers folder: application.rb.

The ApplicationController contains code that can be run in all your controllers and it inherits from Rails ActionController::Base class.

You don't need to worry with the ApplicationController as of yet, so let's just define a few method stubs in book_controller.rb. Based on your requirement, you could define any number of functions in this file.

Modify the file to look like the following and save your changes. Note that it is upto you what name you want to give to these methods, but better to give relevant names.

class BookController < ApplicationController
   def list
   def show
   def new
   def create
   def edit
   def update
   def delete

Now let us implement all the methods one by one.

Implementing the list Method

The list method gives you a printout of all the books in the database. This functionality will be achieved by the following lines of code.

def list
   @books = Book.find(:all)

The @books = Book.find(:all) line in the list method tells Rails to search the books table and store each row it finds in the @books instance object.

Implementing the show Method

The show method displays only further details on a single book. This functionality will be achieved by the following lines of code.

def show
   @book = Book.find(params[:id])

The show method's @books = Book.find(params[:id]) line tells Rails to find only the book that has the id defined in params[:id].

The params object is a container that enables you to pass values between method calls. For example, when you're on the page called by the list method, you can click a link for a specific book, and it passes the id of that book via the params object so that show can find the specific book.

Implementing the new Method

The new method lets Rails know that you will create a new object. So just add the following code in this method.

def new
   @book =
   @subjects = Subject.find(:all)

The above method will be called when you will display a page to the user to take user input. Here second line grabs all the subjects from the database and puts them in an array called @subjects.

Implementing the create Method

Once you take user input using HTML form, it is time to create a record into the database. To achieve this, edit the create method in the book_controller.rb to match the following:

def create
   @book =[:book])
      redirect_to :action ⇒ 'list'
      @subjects = Subject.find(:all)
      render :action ⇒ 'new'

The first line creates a new instance variable called @book that holds a Book object built from the data, the user submitted. The data was passed from the new method to create using the params object.

The next line is a conditional statement that redirects the user to the list method if the object saves correctly to the database. If it doesn't save, the user is sent back to the new method. The redirect_to method is similar to performing a meta refresh on a web page: it automatically forwards you to your destination without any user interaction.

Then @subjects = Subject.find(:all) is required in case it does not save data successfully and it becomes similar case as with new option.

Implementing the edit Method

The edit method looks nearly identical to the show method. Both methods are used to retrieve a single object based on its id and display it on a page. The only difference is that the show method is not editable.

def edit
   @book = Book.find(params[:id])
   @subjects = Subject.find(:all)

This method will be called to display data on the screen to be modified by the user. The second line grabs all the subjects from the database and puts them in an array called @subjects.

Implementing the update Method

This method will be called after the edit method, when the user modifies a data and wants to update the changes into the database. The update method is similar to the create method and will be used to update existing books in the database.

def update
   @book = Book.find(params[:id])
   if @book.update_attributes(params[:book])
      redirect_to :action ⇒ 'show', :id ⇒ @book
      @subjects = Subject.find(:all)
      render :action ⇒ 'edit'

The update_attributes method is similar to the save method used by create but instead of creating a new row in the database, it overwrites the attributes of the existing row.

Then @subjects = Subject.find(:all) line is required in case it does not save the data successfully, then it becomes similar to edit option.

Implementing the delete Method

If you want to delete a record from the database then you will use this method. Implement this method as follows.

def delete
   redirect_to :action ⇒ 'list'

The first line finds the classified based on the parameter passed via the params object and then deletes it using the destroy method. The second line redirects the user to the list method using a redirect_to call.

Additional Methods to Display Subjects

Assume you want to give a facility to your users to browse all the books based on a given subject. So, you can create a method inside book_controller.rb to display all the subjects. Assume the method name is show_subjects:

def show_subjects
   @subject = Subject.find(params[:id])

Finally your book_controller.rb file will look as follows:

class BookController < ApplicationController
   def list
      @books = Book.find(:all)
   def show
      @book = Book.find(params[:id])
   def new
      @book =
      @subjects = Subject.find(:all)
   def create
      @book =[:book])
         redirect_to :action ⇒ 'list'
         @subjects = Subject.find(:all)
         render :action ⇒ 'new'

   def edit
      @book = Book.find(params[:id])
      @subjects = Subject.find(:all)
   def update
      @book = Book.find(params[:id])
      if @book.update_attributes(params[:book])
         redirect_to :action ⇒ 'show', :id ⇒ @book
         @subjects = Subject.find(:all)
         render :action ⇒ 'edit'

   def delete
      redirect_to :action ⇒ 'list'

   def show_subjects
      @subject = Subject.find(params[:id])

Now save your controller file and come out for the next assignment.

What is Next?

You have created almost all the methods, which will work on backend. Next we will create the code to generate screens to display data and to take input from the user.

Rails Views - ActionView

A Rails View is an ERb program that shares data with controllers through mutually accessible variables.

If you look in the app/views directory of the library application, you will see one subdirectory for each of the controllers we have created: book. Each of these subdirectories was created automatically when the same-named controller was created with the generate script.

Now, assuming your web server is up and running, try to input the following in your browser's address box:


You get the following error message because you have not defined any view file for any method defined in the controller.

Missing Template

Rails let's you know that you need to create the view file for the new method. Each method you define in the controller needs to have a corresponding html.erb file, with the same name as the method, to display the data that the method is collecting.

So let's create view files for all the methods we have defined in the book_controller.rb.

Creating View File for list Method

Create a file called list.html.erb using your favorite text editor and save it to app/views/book. After creating and saving the file, refresh your web browser. You should see a blank page; if you don't, check the spelling of your file and make sure that it is exactly the same as your controller's method.

Now, display the actual content. Let us put the following code into list.html.erb.

<% if @books.blank? %>
<p>There are not any books currently in the system.</p>
<% else %>
<p>These are the current books in our system</p>

<ul id="books">
   <% @books.each do |c| %>
   <li><%= link_to c.title, {:action => 'show', :id =>} -%></li>
   <% end %>

<% end %>
<p><%= link_to "Add new Book", {:action => 'new' }%></p>

The code to be executed is to check whether the @books array has any objects in it. The .blank? method returns true if the array is empty, and false if it contains any objects. This @books object was created in controller inside the list method.

The code between the <%= %> tags is a link_to method call. The first parameter of link_to is the text to be displayed between the <a> tags. The second parameter is what action is called when the link is clicked. In this case, it is the show method. The final parameter is the id of the book that is passed via the params object.

Now, try refreshing your browser and you should get the following screen because we don't have any book in our library.

No Book Message

Creating View File for new Method

Till now, we don't have any book in our library. We have to create few books in the system. So, let us design a view corresponding to the new method defined in the book_controller.rb.

Create a file called new.html.erb using your favorite text editor and save it to app/views/book. Add the following code to the new.html.erb file.

<h1>Add new book</h1>
<%= start_form_tag :action ⇒ 'create' %>

<p><label for="book_title">Title</label>:
<%= text_field 'book', 'title' %></p>

<p><label for="book_price">Price</label>:
<%= text_field 'book', 'price' %></p>

<p><label for="book_subject">Subject</label>:
<%= collection_select(:book,:subject_id,@subjects,:id,:name) %></p>

<p><label for="book_description">Description</label><br/>
<%= text_area 'book', 'description' %></p>

<%= submit_tag "Create" %>
<%= end_form_tag %>
<%= link_to 'Back', {:action => 'list'} %>

Here start_form_tag() method interprets the Ruby code into a regular HTML <form> tag using all the information supplied to it. This tag, for example, outputs the following HTML:

<form action="/book/create" method="post">

Next method is text_field that outputs an <input> text field. The parameters for text_field are object and field name. In this case, the object is book and the name is title.

Rails method called collection_select, creates an HTML select menu built from an array, such as the @books one. There are five parameters, which are as follows:

  • :book - The object you are manipulating. In this case, it's a book object.

  • :subject_id - The field that is populated when the book is saved.

  • @books - The array you are working with.

  • :id - The value that is stored in the database. In terms of HTML, this is the <option> tag's value parameter.

  • :name - The output that the user sees in the pull-down menu. This is the value between the <option> tags.

The next used is submit_tag, which outputs an <input> button that submits the form. Finally, there is the end_form_tag method that simply translates into </form>.

Go to your browser and visit http://localhost:3000/book/new. This will give you the following screen.

New Book

Enter some data in this form and then click at Create button. This will result in a call to create method, which does not need any view because this method is using either list or new methods to view the results. So, when you click at Create button, the data should submit successfully and redirect you to the list page, in which you now have a single item listed as follows:

Create Book

If you click the link, you should see another Template is missing error, since you haven't created the template file for show method yet.

Creating View File for show Method

This method will display the complete detail about any book available in the library. Create a show.html.erb file under app/views/book and populate it with the following code:

<h1><%= @book.title %></h1>

<p><strong>Price: </strong> $<%= @book.price %><br />
<strong>Subject :</strong> <%= %><br />
<strong>Created Date:</strong> <%= @book.created_at %><br />

<p><%= @book.description %></p>

<hr />

<%= link_to 'Back', {:action => 'list'} %>

This is the first time you have taken the full advantage of associations, which enable you to easily pull data from related objects.

The format used is @variable.relatedObject.column. In this instance, you can pull the subject's name value through the @book variable using the belongs_to associations. If click on any listed record then it will show you the following screen.

Show Book

Creating View File for edit Method

Create a new file called edit.html.erb and save it in app/views/book. Populate it with the following code:

<h1>Edit Book Detail</h1>
<%= start_form_tag :action ⇒ 'update', :id ⇒ @book %>

<p><label for = "book_title">Title</label>:
<%= text_field 'book', 'title' %></p>

<p><label for = "book_price">Price</label>:
<%= text_field 'book', 'price' %></p>

<p><label for = "book_subject">Subject</label>:
<%= collection_select(:book, :subject_id, @subjects, :id, :name) %></p>

<p><label for = "book_description">Description</label><br/>
<%= text_area 'book', 'description' %></p>

<%= submit_tag "Save changes" %>
<%= end_form_tag %>
<%= link_to 'Back', {:action ⇒ 'list' } %>

This code is very similar to the new method except action to be updated instead of creating and defining an id.

At this point, we need some modification in the list method's view file. Go to the <li></li> element and modify it to look like the following:

   <%= link_to c.title, {:action ⇒ "show", :id ⇒} -%>
   <b> <%= link_to 'Edit', {:action ⇒ "edit",
   :id ⇒} %></b>

Now, try to browse books using the http://localhost:3000/book/list. It will give you the listing of all the books along with Edit option. When you click the Edit option, then you will have next screen as follows:

Edit Book

Now, you edit this information and then click at Save Changes button. This will result in a call to update method available in the controller file and it will update all the changed attribute. Notice that the update method does not need any view file because it's using either show or edit methods to show its results.

Creating View File for delete Method

Removing information from a database using Ruby on Rails is almost too easy. You do not need to write any view code for the delete method because this method is using list method to display the result. So, let's just modify list.html.erb again and add a delete link.

Go to the <li></li> element and modify it to look like the following:

   <%= link_to c.title, {:action ⇒ 'show', :id ⇒} -%>
   <b> <%= link_to 'Edit', {:action ⇒ 'edit', :id ⇒} %></b>
   <b> <%= link_to "Delete", {:action ⇒ 'delete', :id ⇒},
   :confirm ⇒ "Are you sure you want to delete this item?" %></b>

The :confirm parameter presents a JavaScript confirmation box asking if you really want to perform the action. If the user clicks OK, the action proceeds, and the item is deleted.

Now, try browsing books using http://localhost:3000/book/list. It will give you listing of all the books along with Edit and Delete options as follows:

Delete Book

Now using the Delete option, you can delete any listed record.

Creating View File for show_subjects Method

Create a new file, show_subjects.html.erb, in the app/views/book directory and add the following code to it:

<h1><%= -%></h1>

   <% @subject.books.each do |c| %>
   <li><%= link_to c.title, :action ⇒ "show", :id ⇒ -%></li>
   <% end %>

You are taking advantage of associations by iterating through a single subject's many books listings.

Now modify the Subject: line of show.html.erb so that the subject listing shows a link.

<strong>Subject: </strong> <%= link_to,
:action ⇒ "show_subjects", :id ⇒ %><br />

This will output a list of subject on the index page, so that users can access them directly.

Modify list.html.erb to add the following to the top of the file:

<ul id="subjects">
   <% Subject.find(:all).each do |c| %>
   <li><%= link_to, :action ⇒ "show_subjects", :id ⇒ %></li>
   <% end %>

Now try browsing books using http://localhost:3000/book/list. It will display all subjects with links so that you can browse all the books related to that subject.

List Subjects

What is Next?

Hope now you are feeling comfortable with all the operations of Rails.

The next chapter explains how to use Layouts to put your data in a better way. We will show you how to use CSS in your Rails applications.

Rails - Layouts

A layout defines the surroundings of an HTML page. It's the place to define a common look and feel of your final output. Layout files reside in app/views/layouts.

The process involves defining a layout template and then letting the controller know that it exists and to use it. First, let's create the template.

Add a new file called standard.html.erb to app/views/layouts. You let the controllers know what template to use by the name of the file, so following a same naming scheme is advised.

Add the following code to the new standard.html.erb file and save your changes:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="">

      <meta http-equiv = "Content-Type" content = "text/html;.charset = iso-8859-1" />
      <meta http-equiv = "Content-Language" content = "en-us" />
      <title>Library Info System</title>
      <%= stylesheet_link_tag "style" %>

   <body id="library">
      <div id="container">
         <div id="header">
            <h1>Library Info System</h1>
            <h3>Library powered by Ruby on Rails</h3>

         <div id="content">
            <%= yield -%>

         <div id="sidebar"></div>

Everything you just added were standard HTML elements except two lines. The stylesheet_link_tag helper method outputs a stylesheet <link>. In this instance, we are linking style.css style sheet. The yield command lets Rails know that it should put the html.erb for the method called here.

Now open book_controller.rb and add the following line just below the first line:

class BookController < ApplicationController
layout 'standard'
def list
@books = Book.find(:all)

It instructs the controller that we want to use a layout available in the standard.html.erb file. Now try browsing books that will produce the following screen.

Layout Example

Adding Style Sheet

Till now, we have not created any style sheet, so Rails is using the default style sheet. Now let's create a new file called style.css and save it in /public/stylesheets. Add the following code to this file.

body {
   font-family: Helvetica, Geneva, Arial, sans-serif;
   font-size: small;
   font-color: #000;
   background-color: #fff;

a:link, a:active, a:visited {
   color: #CD0000;

input { 
   margin-bottom: 5px;

p { 
   line-height: 150%;

div#container {
   width: 760px;
   margin: 0 auto;

div#header {
   text-align: center;
   padding-bottom: 15px;

div#content {
   float: left;
   width: 450px;
   padding: 10px;

div#content h3 {
   margin-top: 15px;

ul#books {
   list-style-type: none;

ul#books li {
   line-height: 140%;

div#sidebar {
   width: 200px;
   margin-left: 480px;

ul#subjects {
   width: 700px;
   text-align: center;
   padding: 5px;
   background-color: #ececec;
   border: 1px solid #ccc;
   margin-bottom: 20px;

ul#subjects li {
   display: inline;
   padding-left: 5px;

Now refresh your browser and see the difference:

Layout Example

What is Next?

The next chapter explains how to develop applications using Rails Scaffolding to give user access to add, delete, and modify the records in any database.

Rails - Scaffolding

While you're developing Rails applications, especially those which are mainly providing you with a simple interface to data in a database, it can often be useful to use the scaffold method.

Scaffolding provides more than cheap demo thrills. Here are some benefits:

  • You can quickly get code in front of your users for feedback.
  • You are motivated by faster success.
  • You can learn how Rails works by looking at the generated code.
  • You can use scaffolding as a foundation to jumpstart your development.

Scaffolding Example

To understand scaffolding, let's create a database called cookbook and a table called recipes.

Creating an Empty Rails Web Application

Open a command window and navigate to where you want to create this cookbook web application. We have used c:\ruby. So, run the following command to create a complete directory structure.

C:\ruby> rails cookbook

Setting Up the Database

Here is the way to create a database:

mysql> create database cookbook;
Query OK, 1 row affected (0.01 sec)

mysql> grant all privileges on cookbook.*
to 'root'@'localhost' identified by 'password';
Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

To instruct Rails how to find the database, edit the configuration file c:\ruby\cookbook\config\database.yml and change the database name to cookbook. Leave the password empty. When you finish, it should look as follows:

   adapter: mysql
   database: cookbook
   username: root
   password: [password]
   host: localhost
   adapter: mysql
   database: cookbook
   username: root
   password: [password]
   host: localhost
   adapter: mysql
   database: cookbook
   username: root
   password: [password]
   host: localhost

Rails lets you run in the development mode, test mode, or production mode, using different databases. This application uses the same database for each.

Creating the Database Tables

We will use the following table for our practical purpose. So, create recipes table from SQL prompt as follows:

mysql> USE cookbook;
Changed database

mysql> CREATE TABLE recipes (
   -> title VARCHAR(40),
   -> instructions VARCHAR(255),
   -> PRIMARY KEY (id));
Query OK, 0 rows affected (0.06 Sec)

NOTE: If you wish, you can use Rails Migrations to create and maintain tables.

Creating the Model

First, create a Recipe model class that will hold the data from the recipes table in the database. Use the following command inside the cookbook directory.

C:\ruby\cookbook > ruby script\generate model Recipe

Notice that you are capitalizing Recipe using the singular form. This is a Rails paradigm that you should follow each time you create a model.

This will create a file named app/models/recipe.rb, containing a skeleton definition for the Recipe class.

Creating the Controller

Now we have to create a recipe controller with actions to manipulate the recipes in the database via the standard CRUD operations: create, read, update, and delete.

C:\ruby\cookbook > ruby script\generate controller Recipe

Notice that you are capitalizing Recipe using the singular form. This is a Rails paradigm that you should follow each time you create a controller.

This will create a file named app/controllers/recipe_controller.rb, containing a skeleton definition for the RecipeController class. Edit this file and add the line scaffold:recipe as shown below:

class RecipeController < ApplicationController

This single line of code will bring the database table to life. It will provide with a simple interface to your data, and ways of:

  • Creating new entries
  • Editing current entries
  • Viewing current entries
  • Destroying current entries

When creating or editing an entry, scaffold will do all the hard work like form generation and handling for you, and will even provide clever form generation, supporting the following types of inputs:

  • Simple text strings
  • Text areas (or large blocks of text)
  • Date selectors
  • Date-time selectors

Now, go to the cookbook directory and run the Web Server using the following command:

C:\ruby\cookbook> ruby script/server

Now, open a browser and navigate to This will provide you a screen to create new entries in the recipes table. A screen shot is shown below:

Create Recipe

Once you press the Create button to create a new recipe, your record is added into recipes table and it shows the following result:

Create Recipe

You can see the option to edit, show and destroy the records. So, play around with these options.

You can also list down all the recipes available in the recipes table using the URL

Enhancing the Model

Rails gives you a lot of error handling for free. To understand this, add some validation rules to the empty recipe model:

Modify app/models/recipe.rb as follows and then test your application:

class Recipe < ActiveRecord::Base
   validates_length_of :title, :within ⇒ 1..20
   validates_uniqueness_of :title, :message ⇒ "already exists"

These entries will give automatic checking.

  • validates_length_of - the field is not blank and not too long.

  • validates_uniqueness_of - duplicate values are trapped. Instead of the default Rails error message, we have given a custom message here.

The Generated Scaffold Code

With the scaffold action, Rails generates all the code it needs dynamically. By running scaffold as a script, we can get all the code written to disk, where we can investigate it and then start tailoring it to our requirements.

So now, let's start once again to generate Scaffold code manually by using the scaffold helper script:

C:\ruby\cookbook> ruby script/generate scaffold recipe

exists  app/controllers/
exists  app/helpers/
create  app/views/recipes
exists  app/views/layouts/
exists  test/functional/
dependency  model

exists    app/models/
exists    test/unit/
exists    test/fixtures/

identical    app/models/recipe.rb
identical    test/unit/recipe_test.rb
identical    test/fixtures/recipes.yml

create  app/views/recipes/_form.html.erb
create  app/views/recipes/list.html.erb
create  app/views/recipes/show.html.erb
create  app/views/recipes/new.html.erb
create  app/views/recipes/edit.html.erb

create  app/controllers/recipes_controller.rb

create  test/functional/recipes_controller_test.rb
create  app/helpers/recipes_helper.rb
create  app/views/layouts/recipes.html.erb

create  public/stylesheets/scaffold.css

The Controller

Let's look at the code behind the controller. This code is generated by the scaffold generator. If you open app/controllers/recipes_controller.rb, then you will find something as follows:

class RecipesController > ApplicationController
   def index
      render :action ⇒ 'list'

   verify :method ⇒ :post, :only ⇒ [ :destroy, :create, :update ],
   :redirect_to ⇒ { :action ⇒ :list }

   def list
      @recipe_pages, @recipes = paginate :recipes, :per_page ⇒ 10

   def show
      @recipe = Recipe.find(params[:id])

   def new
      @recipe =

   def create
      @recipe =[:recipe])
         flash[:notice] = 'Recipe was successfully created.'
         redirect_to :action ⇒ 'list'
         render :action ⇒ 'new'

   def edit
      @recipe = Recipe.find(params[:id])

   def update
      @recipe = Recipe.find(params[:id])
      if @recipe.update_attributes(params[:recipe])
         flash[:notice] = 'Recipe was successfully updated.'
         redirect_to :action ⇒ 'show', :id ⇒ @recipe
         render :action ⇒ 'edit'

   def destroy
      redirect_to :action ⇒ 'list'

When the user of a Rails application selects an action. e.g. "Show" - the controller will execute any code in the appropriate section - "def show" - and then by default will render a template of the same name - "show.rthml". This default behavior can be overwritten.

The controller uses ActiveRecord methods such as find, find_all, new, save, update_attributes, and destroy to move data to and from the database tables. Note that you do not have to write any SQL statements, rails will take care of it automatically.

The Views

All the views and corresponding all the controller methods are created by scaffold command and they are available in the app/views/recipes directory.

How Scaffolding is Different?

If you have gone through the previous chapters, then you must have seen that we had created methods to list, show, delete and create data etc., but scaffolding does that job automatically.

AJAX on Rails Tutorial

Ajax stands for Asynchronous JavaScript and XML. Ajax is not a single technology; it is a suite of several technologies. Ajax incorporates the following:

  • XHTML for the markup of web pages
  • CSS for the styling
  • Dynamic display and interaction using the DOM
  • Data manipulation and interchange using XML
  • Data retrieval using XMLHttpRequest
  • JavaScript as the glue that meshes all this together

Ajax enables you to retrieve data for a web page without having to refresh the contents of the entire page. In the basic web architecture, the user clicks a link or submits a form. The form is submitted to the server, which then sends back a response. The response is then displayed for the user on a new page.

When you interact with an Ajax-powered web page, it loads an Ajax engine in the background. The engine is written in JavaScript and its responsibility is to both communicate with the web server and display the results to the user. When you submit data using an Ajax-powered form, the server returns an HTML fragment that contains the server's response and displays only the data that is new or changed as opposed to refreshing the entire page.

For a complete detail on AJAX you can go through our AJAX Tutorial

How Rails Implements Ajax

Rails has a simple, consistent model for how it implements Ajax operations. Once the browser has rendered and displayed the initial web page, different user actions cause it to display a new web page (like any traditional web application) or trigger an Ajax operation:

  • Some trigger fires - This trigger could be the user clicking on a button or link, the user making changes to the data on a form or in a field, or just a periodic trigger (based on a timer).

  • The web client calls the server - A JavaScript method, XMLHttpRequest, sends data associated with the trigger to an action handler on the server. The data might be the ID of a checkbox, the text in an entry field, or a whole form.

  • The server does processing - The server-side action handler ( Rails controller action )-- does something with the data and returns an HTML fragment to the web client.

  • The client receives the response - The client-side JavaScript, which Rails creates automatically, receives the HTML fragment and uses it to update a specified part of the current page's HTML, often the content of a <div> tag.

These steps are the simplest way to use Ajax in a Rails application, but with a little extra work, you can have the server return any kind of data in response to an Ajax request, and you can create custom JavaScript in the browser to perform more involved interactions.

AJAX Example

While discussing rest of the Rails concepts, we have taken an example of Library. There we have a table called subject and we have added few subjects at the time of Migration. Till now we have not provided any procedure to add and delete subjects in this table.

In this example, we will provide, list, show and create operations on subject table. If you don't have any understanding on Library Info System explained in the previous chapters, then we would suggest you to go through the previous chapters first and then continue with AJAX on Rails.

Creating the Controller

Let us start with the creation of a controller for subject. It will be done as follows:

C:\ruby\library> ruby script/generate controller Subject

The above command creates a controller file app/controllers/subject_controller.rb. Open this file in any text editor and modify it to have the following content:

class SubjectController < ApplicationController
   layout 'standard'

   def list
   def show
   def create

Now we will give implementation for all these functions in the same way we had given in the previous chapters.

The list Method Implementation

def list
   @subjects = Subject.find(:all)

This is similar to the example explained earlier and will be used to list down all the subjects available in our database.

The show Method Implementation

def show
   @subject = Subject.find(params[:id])

This is also similar to the example explained earlier and will be used to display a particular subject corresponding to the passed ID.

The create Method Implementation

def create
   @subject =[:subject])
      render :partial ⇒ 'subject', :object ⇒ @subject

This is a bit new here. Here we are not redirecting a page to any other page, but just rendering only the changed part instead of the whole page.

It happens only when using partial. We don't write the complete view file, instead we will write a partial in the /app/view/subject directory. We will see it in a moment. First let's create the view files for other methods.

Creating Views

Now, we will create view files for all the methods except for the create method for which we will create a partial.

Creating View for list Method

Create a file list.html.erb in the /app/view/subject and populate it with the following code.

<h1>Listing Subjects</h1>

<ul id="subject_list">
   <% @subjects.each do |c| %>
   <li><%= link_to, :action ⇒ 'show', :id ⇒ %>
   <%= "(#{c.books.count})" -%></li>
   <% end %>

Here you are iterating through the @subjects array and outputting a <li> element containing a link to the subject it is referencing for each item in the array. Additionally, you are outputting the number of books in that specific subject inside parentheses. Rails' associations make it easy to step through a relationship and get information like this.

Now, try browsing your Subject list using http://localhost:3000/subject/list. It will show you the following screen.

List Subjects

Creating View for show Method

Create a file show.html.erb in the /app/view/subject and populate it with the following code.

<h1><%= -%></h1>

   <% @subject.books.each do |c| %>
   <%= link_to c.title, :controller ⇒ "book", :action ⇒ "show",:id ⇒ -%>
   <% end %>

Now try clicking on any subject and you will find a listing of all the books available under that subject.

Creating View for create Method

We would not create a view for create method, because we are using partial instead of view. So, in the next section we will create a partial for the create method.

Adding Ajax Support

To get Ajax support in the Rails application, you need to include the necessary JavaScript files in the layout. Rails is bundled with several libraries that make using Ajax very easy. Two libraries prototype and are very popular.

To add Prototype and support to the application, open up the standard.html.erb layout file in app/views/layouts, add the following line just before the </head> tag, and save your changes:

<%= javascript_include_tag :defaults %>

This includes both the Prototype and libraries in the template, so their effects will be accessible from any of the views.

Now, add the following code at the bottom of app/views/subject/list.html.erb.

<p id="add_link"><%= link_to_function("Add a Subject",

<div id="add_subject" style="display:none;">
   <%= form_remote_tag(:url ⇒ {:action ⇒ 'create'},
      :update ⇒ "subject_list", :position ⇒ :bottom,
      :html ⇒ {:id ⇒ 'subject_form'})%>
   Name: <%= text_field "subject", "name" %>
   <%= submit_tag 'Add' %>
   <%= end_form_tag %>

We are using link_to_function instead of link_to method because the link_to_function method enables you to harness the power of the Prototype JavaScript library to do some neat DOM manipulations.

The second section is the creation of the add_subject <div>. Notice that you set its visibility to be hidden by default, using the CSS display property. The preceding link_to_function is what will change this property and show the <div> to the user to take the input required to add a new subject.

Next, you are creating the Ajax form using the form_remote_tag. This Rails helper is similar to the start_form_tag tag, but it is used here to let the Rails framework know that it needs to trigger an Ajax action for this method. The form_remote_tag takes the :action parameter just like start_form_tag.

You also have two additional parameters: :update and :position.

  • The :update parameter tells Rails' Ajax engine which element to update based on its id. In this case, it's the <ul> tag.

  • The :position parameter tells the engine where to place the newly added object in the DOM. You can set it to be at the bottom of the unordered list (:bottom) or at the top (:top).

Next, you create the standard form fields and submit buttons as before and then wrap things up with an end_form_tag to close the <form> tag. Make sure that things are semantically correct and valid XHTML.

Creating partial for create Method

We are calling the create method while adding a subject and inside this create method, we are using one partial. So let's implement this partial before going for the actual practical.

Under app/views/subject, create a new file called _subject.html.erb. Notice that all the partials are named with an underscore (_) at the beginning.

Add the following code into this file:

<li id="subject_<%= %>">
   <%= link_to, :action ⇒ 'show', :id ⇒ %>
   <%= "(#{subject.books.count})" -%>

You are done now and can easily add several subjects without having to wait for the page to refresh after each subject is added. Now, try browsing your Subject list using http://localhost:3000/subject/list. It will show you the following screen. Try to add some subject.

Add Subject

When you press the Add button, subject would be added at the bottom of all the available subjects and you would not have a feel of a page refresh.

File Uploading using Rails

You may have a requirement in which you want your site visitors to upload a file on your server. Rails makes it very easy to handle this requirement. Now we will proceed with a simple and small Rails project.

As usual, let's start off with a new Rails application called upload. Let's create the basic structure of the application by using simple rails command.

C:\ruby> rails upload

Now, let's decide where you would like to save your uploaded files. Assume this is data directory inside your public section. Create this directory and check the permissions.

C:\ruby> cd upload
C:\ruby> mkdir upload\public\data

Our next step will be as usual, to create the controller and the models.

Creating the Model

Because this is not a database-based application, we can keep whatever name that is comfortable to us. Let’s assume we have to create a DataFile model.

C:\ruby> ruby script/generate model DataFile
exists  app/models/
exists  test/unit/
exists  test/fixtures/

create  app/models/data_file.rb
create  test/unit/data_file_test.rb
create  test/fixtures/data_files.yml

create  db/migrate
create  db/migrate/001_create_data_files.rb

Now, we will create a method called save in the data_file.rb model file. This method will be called by the application controller.

class DataFile < ActiveRecord::Base

   name =  upload['datafile'].original_filename
   directory = "public/data"

   # create the file path
   path = File.join(directory, name)

   # write the file, "wb") { |f| f.write(upload['datafile'].read) }


The above function will take the CGI object upload and will extract uploaded file name using helper function original_filename and finally it will store the uploaded file into "public/data" directory. You can call the helper function content_type to know the media type of the uploaded file.

Here File is a ruby object and join is a helper function that will concatenate the directory name along with file the name and will return the full file path.

Next, to open a file in the write mode, we are using the open helper function provided by the File object. Further we are reading data from the passed data file and writing into output file.

Creating the Controller

Let's create a controller for our upload project:

C:\ruby> ruby script/generate controller Upload
exists  app/controllers/
exists  app/helpers/

create  app/views/upload
exists  test/functional/

create  app/controllers/upload_controller.rb
create  test/functional/upload_controller_test.rb
create  app/helpers/upload_helper.rb

Now, we will create two controller functions. The first function index will call a view file to take user input and the second function uploadFile takes file information from the user and passes it to the 'DataFile' model. We set the upload directory to the 'uploads' directory we created earlier "directory = 'data'".

class UploadController < ApplicationController

   def index
      render :file ⇒ 'app\views\upload\uploadfile.html.erb'
   def uploadFile
      post =[:upload])
      render :text ⇒ "File has been uploaded successfully"

Here we are calling function defined in the model file. The render function is being used to redirect to view file as well as to display a message.

Creating View

Finally, we will create a view file uploadfile.html.erb, which we have mentioned in the controller. Populate this file with the following code:

<h1>File Upload</h1>
<%= start_form_tag ({:action ⇒ 'uploadFile'}, 
   :multipart ⇒ true) %>
<p><label for = "upload_file">Select File</label> : 
<%= file_field 'upload', 'datafile' %></p>
<%= submit_tag "Upload" %>
<%= end_form_tag %>

Here everything is same what we have explained in the earlier chapters. The only new tag is file_field which will create a button to select a file from the user's computer.

By setting the multipart parameter to true, you ensure that your action properly passes along the binary data from the file.

Here, an important point to note is that we have assigned "uploadFile" as the method name in :action, which will be called when you click the Upload button.

It will produce a screen similar to as follows:

Upload File

Now you select a file and upload it. This file will be uploaded into the app/public/data directory with the actual file name and a message will be displayed to you saying that "File has been uploaded successfully".

NOTE: If a file with the same name already exists in your output directory, then it will be over-written.

Files Uploaded from Internet Explorer

Internet Explorer includes the entire path of a file in the filename sent, so the original_filename routine will return something like:

C:\Documents and Files\user_name\Pictures\My File.jpg

instead of just:

My File.jpg

This is easily handled by File.basename, which strips out everything before the filename.

def sanitize_filename(file_name)
# get only the filename, not the whole path (from IE)
just_filename = File.basename(file_name) 
# replace all none alphanumeric, underscore or perioids
# with underscore

Deleting an Existing File

If you want to delete any existing file, it is quite simple. You need to write the following code:

def cleanup
   if File.exist?("#{RAILS_ROOT}/dirname/#{@filename}")

For a complete detail on File object, you need to go through the Ruby Reference Manual.

Send Email using Rails

Action Mailer is the Rails component that enables applications to send and receive emails. In this chapter, we will see how to send an email using Rails. Let’s start creating an emails project using the following command.

C:\ruby\> rails emails

This will create the required framework to proceed. Now, we will start with configuring the Action Mailer.

Action Mailer Configuration

Following are the steps you have to follow to complete your configuration before proceeding with the actual work:

Go to the config folder of your emails project and open environment.rb file and add the following line at the bottom of this file.

ActionMailer::Base.delivery_method = :smtp

It tells ActionMailer that you want to use the SMTP server. You can also set it to be :sendmail if you are using a Unix-based operating system such as Mac OS X or Linux.

Add the following lines of code at the bottom of your environment.rb as well.

ActionMailer::Base.server_settings = {
   :address ⇒ "",
   :port ⇒ 25,
   :domain ⇒ "",
   :authentication ⇒ :login,
   :user_name ⇒ "username",
   :password ⇒ "password",

Replace each hash value with proper settings for your Simple Mail Transfer Protocol (SMTP) server. You can take this information from your Internet Service Provider if you already don't know. You don't need to change port number 25 and authentication type if you are using a standard SMTP server.

You may also change the default email message format. If you prefer to send email in HTML instead of plain text format, add the following line to config/environment.rb as well:

ActionMailer::Base.default_content_type = "text/html"

ActionMailer::Base.default_content_type could be set to "text/plain", "text/html", and "text/enriched". The default value is "text/plain".

The next step will be to create a mailer

Generate a Mailer

Use the following command to generate a mailer as follows:

C:\ruby\> cd emails
C:\ruby\emails> ruby script/generate mailer Emailer

This will create a file emailer.rb in the app\models directory. Check the content of this file as follows:

class Emailer < ActionMailer::Base

Let's create one method as follows:

class Emailer < ActionMailer::Base
   def contact(recipient, subject, message, sent_at =
      @subject = subject
      @recipients = recipient
      @from = ''
      @sent_on = sent_at
         @body["title"] = 'This is title'
         @body["email"] = ''
         @body["message"] = message
      @headers = {}

The contact method has four parameters a recipient, a subject, a message, and a sent_at, which defines when the e-mail is sent. The method also defines six standard parameters that are a part of every ActionMailer method:

  • @subject defines the e-mail subject.

  • @body is a Ruby hash that contains values with which you can populate the mail template. You created three key-value pairs: title, email, and message.

  • @recipients is a list of the people to whom the message is being sent.

  • @from defines who the e-mail is from.

  • @sent_on takes the sent_at parameter and sets the timestamp of the e-mail.

  • @headers is another hash that enables you to modify the e-mail headers. For example, you can set the MIME type of the e-mail if you want to send either plain text or HTML e-mail.

Now, we will create a mailer template, which is just text with standard Rails <%= %> placeholders scattered throughout.

Put the following code in the app/views/contact.html.erb file


You are having one email message from <%= @email %> with a tilte 

<%= @title %>
and following is the message:
<%= @message %>


Next we will create a controller for this application as follows:

C:\ruby\emails> ruby script/generate controller Emailer

Now, let's define a controller method in emailer_controller.rb, which will call the Model method to send the actual email as follows:

class EmailerController < ApplicationController
   def sendmail
      email = @params["email"]
         recipient = email["recipient"]
         subject = email["subject"]
         message = email["message"]
      Emailer.deliver_contact(recipient, subject, message)
      return if request.xhr?
      render :text ⇒ 'Message sent successfully'

To deliver emails using the mailer's contact method, you have to add deliver_ at the beginning of the method name. You add a return - request.xhr?, so that you can escape to Rails Java Script (RJS), if the browser does not support JavaScript and then tell the method to render a text message.

You are almost done except to prepare a screen from where you will get the user information to send email. So, let's define one screen method index in controller and corresponding view:

Add the following code in the emailer_controller.rb file:

def index
   render :file ⇒ 'app\views\emailer\index.html.erb'

Now, let's define our view in app\views\emails\index.html.erb

<h1>Send Email</h1>

<%= start_form_tag :action ⇒ 'sendmail' %>

<p><label for="email_subject">Subject</label>:
<%= text_field 'email', 'subject' %></p>

<p><label for="email_recipient">Recipient</label>:
<%= text_field 'email', 'recipient' %></p>

<p><label for="email_message">Message</label><br/>
<%= text_area 'email', 'message' %></p>

<%= submit_tag "Send" %>
<%= end_form_tag %>

Now, test your application by using It displays the following screen and by using this screen, you will be able to send your message to anybody.

Send Email

This will send your message and will display the text message "Message sent successfully".

For more information on how to send emails using Rails, please go through ActionMailer.