Saturday, 24 May 2014

Rails Database Setup

Before starting with this chapter, make sure your database server is setup and running. Ruby on Rails recommends to create three databases: A database for each 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. I am using root user ID for my application. In MySQL, a console session in which you do this looks something like this:
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)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
You can do same thing for two more databases library_production andlibrary_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:
development:
  adapter: mysql
  database: library_development
  username: root
  password: [password]
  host: localhost
test:
  adapter: mysql
  database: library_test
  username: root
  password: [password]
  host: localhost
production:
  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 ?

Next two chapters will teach you how to model your database tables and how to manage them using Rails Migrations.

Ruby on Rails Examples

Subsequent chapters are based on the example given in this chapter. In this example we will create something simple but operational online library system for holding and managing the books.
Now you have to be patient till you go through next few chapters. I'm sure after completing this tutorial you will have complete understanding on Rails.
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 makes creating and maintaining database tables and columns easy.
  • Write Controller Code to put a life in your application.
  • Create Views to present your data through User Interface.
So lets 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.
  1. Go into ruby installation directory to create your application.
  2. 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 thelibrary/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. This 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 http://127.0.0.1:3000. 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 ?

Next session will teach you how to create databases for your application and what is the configuration required to access these created databases.
Further we will see what is Rail Migration and how it is used to maintain database tables.

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 tell it.
Here is a top level view of directory tree created by 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 demo application created in installation chapter. This can be created using a simple helper commandC:\ruby\> rails demo.
Now go into demo application root directory as follows:
C:\ruby\> cd demo
C:\ruby\demo> dir
You will find a directory structure as follows:
demo/
..../app
......../controller
......../helpers
......../models
......../views
............../layouts
..../components
..../config
..../db
..../doc
..../lib
..../log
..../public
..../script
..../test
..../tmp
..../vendor
README
Rakefile
Now let's explain the purpose of each directory
  • app : This 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 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.rhtml. Inside default.rhtml, 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 theR ubyDoc-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 Rails creates for you all go 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 Ruby installation.

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 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 music store, university, dating service, address book, or hardware inventory. So here you 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 database structure to keep the entities and their relationship.
  • Specify what can happen in this domain: The domain model is static, Now you have to get 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 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 ) :

Maintains the relationship between Object and 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, and so on.

View ( ActionView )

A presentation of data in a particular format, triggered by a controller's decision to present the data. They are script based templating 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, massaging 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:

A Pictorial Diagram of Ruby on Rails Framework is given here:
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 link this:
C:\>cd ruby\lib\ruby\gems\1.8\gems
C:\ruby\lib\ruby\gems\1.8\gems\>dir
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 provide facilities for manipulating and displaying that data. Rails ties it all together.

Friday, 23 May 2014


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 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 music store, university, dating service, address book, or hardware inventory. So here you 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 database structure to keep the entities and their relationship.
  • Specify what can happen in this domain: The domain model is static, Now you have to get 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 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 ) :

Maintains the relationship between Object and 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, and so on.

View ( ActionView )

A presentation of data in a particular format, triggered by a controller's decision to present the data. They are script based templating 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, massaging 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:

A Pictorial Diagram of Ruby on Rails Framework is given here:
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 link this:
C:\>cd ruby\lib\ruby\gems\1.8\gems
C:\ruby\lib\ruby\gems\1.8\gems\>dir
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 provide facilities for manipulating and displaying that data. Rails ties it all together.

Ruby on Rails Installation

To develop a web application using Ruby on Rails Framework, 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 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:

  1. 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.
  2. If Ruby is not installed, then download an installation package fromrubyinstaller.rubyforge.org. 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 alongwith this package. Please check Release Notes for more detail.
  3. With RubyGems loaded, you can install all of Rails and its dependencies through the command line:
C:\> gem install rails --include-dependencies
NOTE: 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:

  1. 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.
  2. Next you have to install RubyGems. Go to rubygems.rubyforge.org 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
  1. Now use RubyGems to install Rails. Still in the Terminal application, issue the following command.
tp> sudo gem install rails --include-dependencies
NOTE: 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:

  1. 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.
  2. Download ruby-x.y.z.tar.gz from www.ruby-lang.org
  3. Untar the distribution, and enter the top-level directory.
  4. 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
  1. Install RubyGems. Go to rubygems.rubyforge.org, 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
  1. Now use RubyGems to install Rails. Still in the shell, issue the following command.
tp> gem install rails --include-dependencies
NOTE: 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 installed Rails using RubyGems, keeping 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 environment is setup or not. Now next use the following command to run WEBrick web server on your machine.
tp> cd demo
tp> ruby script/server
=> Rails application started on http://0.0.0.0:3000
=> 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.
http://localhost:3000
If everything is fine then you should have a message something like "Welcome aboard" or "Congratulations".

Ruby on Rails Introduction

What is Ruby ?

Before we ride on Rails, let's know a little bit about 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.
  • Originated in Japan and Rapidly Gaining Mindshare in US and Europe.

Why Ruby ?

Ruby is becoming popular exponentially in Japan and now in US and Europe as well. Following are greatest factors:
  • Easy to learn
  • Open source (very liberal license)
  • Rich libraries
  • Very easy to extend
  • Truly Object-Oriented
  • Less Coding with fewer bugs
  • Helpful community

Why Not Ruby ?

  • Performance - Although it rivals Perl and Python.
  • Threading model does not use native 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
      end

      def salute
         puts "Hello #{@name}!"
      end
   end
   # Create a new object
   h = Hello.new("Ruby")
   # Output "Hello Ruby!"
   h.salute

Embedded Ruby:

Ruby provides you with a program called ERb (Embedded Ruby), written by Seki Masatoshi. ERb allows you to put Ruby code inside an HTML file. ERb reads along, word for word, and then at a certain point when it sees the Ruby code embedded in the document it sees that it has to fill in a blank, which it does by 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 part of the output, enclose the code between <%= and %>.
Here's an example, Save the code in erbdemo.rb file. Please note that a ruby file will have extension .rb
<% page_title = "Demonstration of ERb" %>
<% salutation = "Dear programmer," %>
<html>
<head>
<title><%= page_title %></title>
</head>
<body>
<p><%= salutation %></p>
<p>This is an example of how ERb fills out a template.</p>
</body>
</html>
Now, run the program using the command-line utility erb
c:\ruby\>erb erbdemo.rb
This will produce following result:
<html>
<head>
<title>Demonstration of ERb</title>
</head>
<body>
<p>Dear programmer,</p>
<p>This is an example  of how ERb fills out a template.</p>
</body>
</html>

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 that all layers are built to work seamlessly together Less Code.
  • Requires fewer total lines of code than other frameworks spend setting up their XML configuration files.

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 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 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.