Learn Ruby and Rails – Full Tutorial For Beginners – 2

ruby on rails

In the previous section, we learn some basic things related to Ruby and rails like what is ruby on rails, How to install it, frameworks, and its directory structure of it. In this section, we start with some basic examples and other topics mentioned below. 

  1. . Database setup
  2. Active Records
  3. Migration 


We will now build an online library system for holding and managing the books that are simple and easy to use.

A basic architecture will be used to build this application, and two ActiveRecord models will be used to describe the types of data stored –

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

Workflow for Creating Rails Applications

The recommended workflow for creating a Rails application is as follows: −

  • Create the skeleton of the application using the rails command.
  • Create a database on the PostgreSQL server to store your data.
  • Set the location of your database and the login credentials for the application.
  • Create Active Records (Models), because these are the business objects you will be working with in your controllers.
  • Produce migrations that simplify the creation and maintenance of database tables and columns.
  • Write controller code to breathe life into your application.
  • Present your data through User Interface by creating views.

Let’s start by creating our library application.

Creating an Empty Rails Web Application

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

  • Create your application in the ruby installation directory.
  • Create a skeleton of a library application using the following command. It will create a directory structure in the current directory.
tp> rails new library

By doing this, you’ll create a subdirectory for the library application containing a complete directory tree of folders and files. Verify the directory structure of the application. Refer to Rails Directory Structure for more information.

Most of our development will take place in the library and app subdirectories.The following is a quick guide to using them – 

  • In the controllers subdirectory, Rails searches for controller classes. A controller handles web requests from users.
  • The views subdirectory holds the display templates that we fill in with data from our application, convert to HTML, and return to the user.
  • The models subdirectory contains classes that model and wraps the data stored in our application’s database. In most frameworks, this part of the application can be messy, tedious, verbose, and prone to errors. Rails make it easy to do.
  • In the helpers subdirectory, you will find classes that assist the model, view, and controller classes. Model, view, and controller code will remain small, focused, and uncluttered.

Starting Web Server

A Rails web application can run under virtually any web server, but the easiest way to develop a Rails web application is to use the built-in WEBrick web server. Let’s start our web server and then browse to our empty library application −

The server will be started from the application directory as follows. The port number is 3000.

tp> cd ruby\library 
tp\ruby\library\> Rails server

It generates the automatic code to start the server as shown below −

Start your WEBrick web server with this command.

Open your browser and navigate to If everything is set up correctly, you should receive a greeting from Webrick. If it does not, then something is wrong with your settings.

1. Database Setup

Before you start this point, make sure your database server is up and running. Ruby on Rails recommends that you create three databases – one each for development, testing, and production. The names of these databases should follow the convention.

  • library_development
  • library_production
  • library_test

Create a user and password for each of them with permissions to read and write. We will use the root user ID for our application.

Database Setup for MySQL

Our application uses the root user ID in MySQL. This is done in the MySQL console as shown below.

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)

Similarly, you can create two more databases, library_production and library_test.

Configuring database.yml

You need to let Rails know the database user name and password at this point. Using the database.yml file in the rails app’s library/config subdirectory, you do this. The file contains live configuration sections for MySQL databases. You need to update the username and password lines in each section to reflect the permissions on the databases you 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

Database Setup for PostgreSQL

PostgreSQL does not provide any users by default. We need to create new users. To create a user with the name rubyuser, run the following command.

tp> sudo -u postgres createuser rubyuser -s

Use the following command to create a password for the new user.

tp> sudo -u postgres psql
postgres=# \password rubyuser

You can create a database library_development by running the following command.

postgres=# CREATE DATABASE library_development OWNER rubyuser; 


For creating a database library_production, run the following command.

postgres=# CREATE DATABASE library_production OWNER rubyuser; 


You can create a database library_test by running the following command.

postgres=# CREATE DATABASE library_test OWNER rubyuser; 


Press Ctrl+D to terminate PosgreSQL.

Configuring database.yml

You need to let Rails know the username and password for the databases at this point. Using the database.yml file in the rails app’s library/config subdirectory, you do this. There are live configuration sections for PostgreSQL databases in this file. Change the username and password lines in each section to reflect the permissions on the databases you have created.

When you finish, it should look as follows −

default: &default
  adapter: postgresql
  encoding: unicode
  adapter: postgresql
  encoding: unicode
  database: library_development
  username: rubyuser
  password: <Password for rubyuser>
  adapter: postgresql
  encoding: unicode
  database: library_test
  username: rubyuser
  password: <Password for rubyuser>
  adapter: postgresql
  encoding: unicode
  database: library_production
  username: rubyuser
  password: <Password for rubyuser>


Rails Active Record is an Object/Relational Mapping (ORM) layer. The model closely follows the standard ORM model, which is as follows −

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

Active Records in Rails provide an interface and binding between the tables in a relational database and Ruby program code used to manipulate database records. The names of Ruby methods are automatically derived from the names of fields in database tables.

CRUD (Create, Read, Update, and Delete) methods are available for each Active Record object. The strategy allows for simple designs and straight forward mappings between database tables and application objects.

Translating a Domain Model into SQL

As long as you remember to write Rails-friendly SQL, transforming a domain model into SQL is generally straightforward. In practice, you must follow certain rules −

  • Every entity (like a book) has a table in the database named after it, but in plural form (books).
  • For each record inserted into such an entity-matching table, there is a field called id, which contains a unique integer.
  • If entity x belongs to entity y, then table y has a field called x_id if entity y belongs to entity x.
  • The bulk of the fields in any table contain the values for the simple properties (anything that’s a number or a string).

Creating Active Record Files (Models)

In order to create the Active Record files for our library entities, introduced in the previous point, run the following command from the top level of the application directory.

library\> rails script/generate model Book
library\> rails script/generate model Subject

The above rails generate model book commands generate the auto code as follows −

To store instances of books and subjects, you request that the generator create models called Book and Subject. It is important to capitalize Book and Subject, as well as using the singular form. Each time you create a model, you should follow this Rails paradigm.

As you use the generate tool, Rails creates the actual model file containing all the methods that make up the model and the business rules you define, a unit test file for 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.

In addition to creating many other files and directories, this will create two files named book.rb and subject.rb containing skeleton definitions 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

There are several models in your rails application, so you need to connect them. You can do this through associations. Active Record offers 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 occurs when a single object can be a member of many other objects. One subject can have many books.
  • many-to-many − Many-to-many relationships exist when a 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.

Your models indicate these associations by adding declarations: has_one, has_many, belongs_to, and has_and_belongs_to_many.

Now, you need to tell Rails which relationships you want to establish within the library data system. Modify book.rb and subject.rb as follows: −

class Book < ActiveRecord::Base
  belongs_to :subject

We The above example uses a singular subject, since a Book can belong to a single Subject.

class Subject < ActiveRecord::Base
  has_many :books

There are often multiple books for one subject, so we’re using plural books.

Implementing Validations on Models

A Rails model implements validations. The data you are entering into the database is defined in the Rails model, so it only makes sense that what valid data is should be defined there as well.

The validations are −

  • The title field should not contain NULL.
  • Price should be a numeric value.

Open the book.rb file in the application/model directory and add the following validations:

class Book < ActiveRecord::Base
  belongs_to :subject
  validates_presence_of :title
  validates_numericality_of :price, :message=>"Error Message"
  • The validates_presence_of – function protects “NOT NULL” fields from missing user input.
  • validates_numericality_of − prevents the user,from entering non numeric data.

Besides the validations mentioned above, there are other common validations.

3. Migration 

Ruby Migration allows you to define changes to your database schema using Ruby, so you can make use of a version control system to keep things synchronized with the code.

There are many uses for this, including −

  • Teams of developers − The other developers just need to update, and run “rake migrate” when one developer updates the schema.
  • Production servers − When you roll out a new release, run “rake migrate” to bring the database up to date as well.
  • Multiple machines − When you develop on both a desktop and a laptop, or at more than one location, migrations can help you keep them all in sync.

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)

Migration supports all the basic data types – The following is a list of data types that migration supports −

  • string −For small data types, such as titles.
  • text − If the textual data is longer, 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 − Only store the date or only store the time.
  • binary −The storage of data such as images, audios, and movies.
  • Boolean − Contains true and false values.

Valid column options are − The following is a list of valid column options.

  • limit ( :limit => “50” )
  • default (:default => “blah” )
  • null (:null => false implies NOT NULL)

NOTE − The activities performed by Rails Migration can be done using any front-end GUI or directly from an SQL prompt, but Rails Migration makes them very easy.

Create the Migrations

The following is the generic syntax for creating a migration:

application_dir> rails generate migration table_name

It will create the file db/migrate/001_table_name.rb. Migration files contain the basic Ruby syntax that describes the data structure of a database table.

NOTE −It is recommended to clean existing migrations generated by model generators before running the migration generator.

We will create two migrations for our three tables − books and subjects.

Books migration should be as follows −

tp> cd library
library> rails generate migration books

The above command generates the following code.

subject migration should be as follows −

tp> cd library
library> rails generate migration subjects

Above command generates the following code.

While creating migrations, notice that you are using lower case for book and subject names. You should follow this Rails paradigm every time you create a Migration.

Edit the Code

Use any simple text editor to edit each file in the db/migrate subdirectory of your application.

Modify 001_books.rb as follows −

You do not need to create the ID column here since it will be created automatically.

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

When migrating to a new version, self.up is used, and self.down is used to roll back any changes made.Currently, the above script will be used to create the 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 script above will create five records in the subjects table.

Run the Migration

Now that you have created all the necessary migration files. Now it’s time to run them against the database.You can do this by opening a command prompt, going to the library directory of the application, and typing rake migrate*

library> rake db:migrate

If it doesn’t exist, the “schema_info” table will be created, which tracks the current version of the database – each new migration will be a new version, and any new migrations will be run until the database is at the latest version.

In Rails, Rake is a Ruby build program that is similar to Unix make, which simplifies the execution of complex tasks, such as updating the structure of a database.

Running Migrations for Production and Test Databases

You can specify what Rails environment to use for the migration using the RAILS_ENV shell variable.

For example −
library> export RAILS_ENV = production
library> rake db:migrate
library> export RAILS_ENV = test
library> rake db:migrate
library> export RAILS_ENV = development
library> rake db:migrate

NOTE − In Windows, use “set RAILS_ENV = production” instead of export.


Leave a Comment

Your email address will not be published. Required fields are marked *