Ruby on Rails Examples


previous next AddThis Social Bookmark Button

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 books. We want our system to:

  • Welcome the visitor with a list of all the books available.
  • Visitor clicks any author's name and be shown all books by that author.
  • Visitor clicks the name of book and be shown all editions of that book.
  • Visitor clicks any edition and be shown details of that edition.

This library application will have following three entities:

  1. BOOK
    • AUTHOR
    • EDITION(S)
    • Title
  2. AUTHOR
    • BOOK (S)
    • First Name
    • Last Name
  3. EDITION
    • BOOK
    • Description
    • Publisher
    • Year
    • Price

To proceed with this example, first we will set up our database. We are going to work with MySQL database. You can choose your database based on your requirement.

Setting up the Database:

We will create three databases: one for development,one for production, and one for testing

  • library_development
  • library_production
  • library_test

You should initialize all three of them and create a user and password on them with full read and write privileges. 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 'userid'@'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 and library_test. 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 config subdirectory of Rails Application you created. This file has live configuration sections for MySQL databases and sample sections for other database systems. In each of the sections you use (the three MySQL sections, if you.re using MySQL as per the examples here), 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: 
  host: localhost
-test:
  adapter: mysql
  database: library_test
  username: root
  password: 
  host: localhost
-production:
  adapter: mysql
  database: library_production
  username: root
  password: 
  host: localhost

NOTE: Check you application/config/database.yml file for this setting.

Designing and creating the database tables:

Translating a domain model into SQL is generally straightforward, 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 AUTHOR) gets a table in the database named after it, but in the plural (AUTHORS).
  • 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).

Using the above rules we will translate all the three entities into SQL form. Following is the SQL script library.SQL to create these three SQL tables.

USE library_development;
DROP TABLE IF EXISTS books;
DROP TABLE IF EXISTS editions;
DROP TABLE IF EXISTS authors;

CREATE TABLE books (
	id INT(11) NOT NULL AUTO_INCREMENT,
	author_id INT(11),
	title VARCHAR(100),
	PRIMARY KEY (id)
);

CREATE TABLE editions (
	id INT(11) NOT NULL AUTO_INCREMENT,
	book_id INT(11) NOT NULL,
	description VARCHAR(30),
	publisher VARCHAR(60),
	year INT(4),
	price FLOAT,
	PRIMARY KEY (id)
);

CREATE TABLE authors (
	id INT(11) NOT NULL AUTO_INCREMENT,
	first_name VARCHAR(25),
	last_name VARCHAR(25),
	PRIMARY KEY (id)
);

Now use following command on command prompt to create above tables.

mysql -u userid -p < library.SQL
password: password

NOTE: You can create these tables at mysql prompt directly or using any other MySQL user Interface.

The library_development database now contains all the three tables.

Adding records to the database:

There are numerous ways to add data to your database, including through Web forms. Here we will create data directly from sql prompt.

mysql> INSERT INTO authors VALUES (1,"Johannes","Brahms");
mysql> INSERT INTO authors VALUES (2,"Claude","Debussy");

mysql> INSERT INTO books VALUES (1,1,"Live with peace");
mysql> INSERT INTO books VALUES (2,2,"Sing a song dear");

mysql> INSERT INTO editions
    -> VALUES 
    -> (1,1,"Facsimile","D. Black Books House", 1998, 21.95);
mysql> INSERT INTO editions
    -> VALUES 
    -> (2,1,"Urtext","Mc Graw Books, Inc.", 1977, 23.50);
mysql> INSERT INTO editions
    -> VALUES 
    -> (3,1,"ed. Y.Matsu","Mc Graw Books, Inc.", 2001, 22.95);
mysql> INSERT INTO editions
    -> VALUES 
    -> (4,2,"","D. Black Books House", 1995, 39.95);
mysql> INSERT INTO editions
    -> VALUES 
    -> (5,2,"Reprint Ed.", "Mc Graw Books, Inc.", 2003, 35.95);

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 to a directory where you want to create your application.
  2. Run the following command to create a skelton for library application.
$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 the model, view, and controller code small, focused, and uncluttered.
  1. A 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 libary application:

Be careful 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 WEBrick web server.

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

To complete the above example you need to work on the following three components:

  1. Creating Models ( Active Records )
  2. Creating Controllers ( Action Controller )
  3. Creating Views ( Action View )

In the subsequent three chapters you will explore Model ( ActiveRecords ), Controller (ActionController) and View (ActionView) concept of Rails.

After completing next three chapters you will have complete understanding on how to develope a web application using Rails and you will be able to design and develope your web application using Rails technology.

previous next Printer Friendly


  

Advertisements



Advertisements