Ruby on Rails (RoR)

Introduction to RoR from


What is Ruby?

Ruby is a pure object-oriented programming language with a super clean syntax that makes programming elegant and fun. Ruby successfully combines Smalltalk's conceptual elegance, Python's ease of use and learning, and Perl's pragmatism. Ruby originated in Japan in the early 1990s, and has started to become popular worldwide in the past few years as more English language books and documentation have become available.

What is Rails?

Rails is an open source Ruby framework for developing database-backed web applications. What's special about that? There are dozens of frameworks out there and most of them have been around much longer than Rails. Why should you care about yet another framework?

What would you think if I told you that you could develop a web application at least ten times faster with Rails than you could with a typical Java framework? You can--without making any sacrifices in the quality of your application! How is this possible?

Part of the answer is in the Ruby programming language. Many things that are very simple to do in Ruby are not even possible in most other languages. Rails takes full advantage of this. The rest of the answer is in two of Rail's guiding principles: less software and convention over configuration.

Less software means you write fewer lines of code to implement your application. Keeping your code small means faster development and fewer bugs, which makes your code easier to understand, maintain, and enhance. Very shortly, you will see how Rails cuts your code burden.

Convention over configuration means an end to verbose XML configuration files--there aren't any in Rails! Instead of configuration files, a Rails application uses a few simple programming conventions that allow it to figure out everything through reflection and discovery. Your application code and your running database already contain everything that Rails needs to know!



Online references for Ruby:

The Ruby official site:

Wikipedia:   (pages 1-5)

Quick reference

String methods (over 100)

Regular expressions (pattern matching)



Online references for RoR:

The RoR official site:


A list of 12 tutorials: (pages 6-10)

RoR database support (called active record)


Notes on RoR Applications

RoR applications have three sections:




There are directory names for each of these sections under:

~rails1/app (assuming you used the name rails1)


The model is the database to be used. RoR uses the relational database model. Mysql is a freeware relational database that we will use. An explanation of relational databases is here. You inform RoR what database to use and its organization via the database.yml  file and the “*.rb” files that you copied into the models directory.


The “views” are the screens to be displayed during execution of your application. Ror uses the same method as PHP. The views files are templates of the screens containing Ruby code between <%     (Ruby code)  %>.  The views for your application are in the directory given the name of your application in the views directory. See the example views in:



The controllers Ruby program defines the class for your application. In the controllers directory will be a program:

ApplicationName_controller.rb (for the example program: example_controller.rb).

Each view has a corresponding method in the class. See the example controller that will be discussed in class.


Installation and execution of the example program on Multilab


Log onto the pen multilab server (

Creation of a mysql database

Your RoR web program will use a mysql relational database. Relational databases are discussed here.


See if you have access to mysql:

paulp@pen:~> which mysql


If you get “command not found”  add its path to your $path system variable:

set path=($path /usr/bin)

This command has to be executed every time you log in unless you add it to your .login shell script. See the CS216 notes on Unix.

When you use mysql, you will be asked for your mysql password.

To start mysql:

 mysql -h mysql –p

You will be asked for your password.

Your mysql account password is stored separately from your multilab password. 

The default password is the same, 'u' followed by the last seven digits of

your student ID number.  It is NOT 'u$' and the last 6 digits. 

NOTE: If you took a previous class and had a mysql ID and changed the password, use that (changed) password. If you do not remember it, send email to: to get it reset back to the default password.

When you are running mysql, the prompt displayed on the screen will be mysql:



You can change your password by logging into mysql and typing:

mysql> set password = password(“yournewpassword”);

mysql commands MUST be terminated by a semicolon. Put your new password in the quotation marks as shown.


You have a database with the same name as your ID. You connect to that database by:

mysql> use yourid;


To create your mysql database, you will execute some batch commands from the command prompt.

Start a new multilab session. In this session:

You can now batch commands to setup your tables. This is done by executing batch file commands that I have provided. Copy the files to your current directory:

cp ~paulp/cs316programs/mysql/*sql   ./

This copies the files





In these files, change the first line:

USE paulp;



where YOUR_ID is your ID on multilab.

You can now create your tables by:

>mysql -h mysql –p  < build_tables.sql


You fill the rows of the tables by:

>mysql -h mysql –p  < fill_tables.sql


To start over, you can drop the created tables:

>mysql -h mysql –p  < drop_tables.sql

But don’t do this now.


Back in the session where mysql is running:

To verify your mysql database, connect to that database by (from your mysql screen):

mysql> use yourid


You can now see what tables have been created:


You should see:


| Tables_in_     |


| customers       |

| orderliness     |

| orders            |

| salesreps         |


2 rows in set (0.00 sec)

After “Tables_in” will be the name of your database (the same name as your ID).


If you are familiar with SQL, you can enter any SQL queries. You do not have to know anything about SQL for this assignment. A useful query  to see the contents of a table:

mysql> select * from customers;

This should display the rows of the customers table:


| id  | last_name | first_name | balance | credit_limit | sales_rep |


| 124 | Adams     | Sally      |  818.75 |         1000 | 03        |

| 256 | Samuels   | Ann        |    21.5 |         1500 | 06        |

| 311 | Charels   | Don        |  825.75 |         1000 | 12        |

| 315 | Daniels   | Tom        |  770.75 |          750 | 06        |

| 405 | Williams  | Al         |  402.75 |         1500 | 12        |

| 412 | Adams     | Sally      |  1817.5 |         2000 | 03        |

| 522 | Nelson    | Mary       |   98.75 |         1500 | 12        |

| 567 | Dinh      | Tran       |   402.4 |          750 | 00        |

| 587 | Galvez    | Mara       |   114.6 |         1000 | 06        |

| 622 | Martin    | Dan        | 1045.75 |         1000 | 03        |


10 rows in set (0.00 sec)


The column headers are the names of the fields in the table. Now display the saleresreps, orders, and orderlines tables by using its name in place of customers.


You use the select/from/where syntax to extract data from the database. For example, to display all data for customer 124:

mysql> select * from customers where id=124;


To display the last name and first name:

mysql>  select last_name,first_name  from customers where id=124;


A relational database has relations (connections) between the tables. The salesreps table is connected to the customers table by the sales_rep column. To display the name of the sales_rep for customer 124:

mysql> select salesreps.last_name from salesreps,customers where and;


The customers table is connected to the orders table by customer number. To display all orders for customer 522:

mysql> select from customers,orders where and;


You can quit mysql:

mysql> quit;


Note that mysql does not have to be running on your Multilab ID for RoR to use it. You only start mysql on your ID for creating and maintaining the tables. Once you have executed the above batch commands to create and fill the tables, you are done with mysql.  After completion of these steps, the table data in the mysql database is the same as displayed in this file: tables.txt.

Creating an RoR application

From your home directory execute these threee commands in this order (the % and $ are displayed by Linux. What you enter is in bold type):

% bash
$ source /usr/local/rvm/scripts/rvm (do not type $ note the space between source and /)
$ rails new rails1 --database=mysql (or some other name instead of rails1 for the root directory for RoR)

This creates directory rails1 with a number of RoR subdirectories. You may get the failure:

         run  bundle install

Your user account isn't allowed to install to the system Rubygems.
(more text)


Press ctlr-C to end the install.

Change directory to the rails1 directory (assuming that is the name you used):

$cd ~/rails1

Edit the rails1/Gemfile:

Change the line:

gem 'mysql2'


gem 'mysql2', '0.3.17'

Execute this command from the rails1 directory:

bundle install --path vendor/bundle

It will take a few minutes to complete. When it does:

Copy the database definition files to your RoR models directories. Copy:

$cp ~paulp/cs316programs/mysql/*.rb    app/models/

Copy the database configuration file to the config directory:

>cp ~paulp/cs316programs/rails/database.yml   config

In this file, change the following lines (marked with CS316 in the comments):

  database: xxxx # CS 316 change to your multilab ID

username: xxxx # CS 316 change to your multilab ID

password: xxxxx # CS 316 change to your mysql (NOT multilab) password

 Add routing information to the routes file. In the file routes.rb in the config directory, add these two lines after the first line (Rails.application.routes.draw do):

get '/example/', to: 'example#index'

post '/example/result', to: 'example#result'

The first line routes requests for the example web page to the index method of the example controller (example_controller.rb).

The second line is used when the user presses the submit button on the example web page, to route the request to the example result method in example_controller.rb.

You will be running your Ruby on Rails server on a Multilab port. Every student must use a different port number (> 1024). To ensure that each student uses a different port number:

  1. Use the last four digits of your student number,  UNLESS:

  2. If the four digits start with 0, use 2 as the highest digit


If your student number is 123456789, your port number is 6789.

If your student number is 123450789, your port number is 2789.

Start the RoR server from the rails1 directory:

~/rails1$ rails server --port=xxxx --binding=

where xxxx is your port number.

This may take a few minutes. You will see messages:

=> Booting WEBrick

=> Rails 4.2.4 application starting in development on

=> Run `rails server -h` for more startup options

=> Ctrl-C to shutdown server

[2015-11-18 12:00:08] INFO WEBrick 1.3.1

[2015-11-18 12:00:08] INFO ruby 2.2.1 (2015-02-26) [x86_64-linux]

[2015-11-18 12:00:08] INFO WEBrick::HTTPServer#start: pid=4963 port=1234

Using another pen logon, you can verify that your Ruby on Rails server is running on your port via the netstat command:

netstat –aep | grep USER_ID

From a browser access: (where xxxx is your port number)

You should see the RoR welcome page.

 Copy my RoR web example controller to the app controllers directory

>cp ~paulp/cs316programs/rails/example_controller.rb  app/controllers


Make the directory example in the views directory:

mkdir ~/rails1/app/views/example

(assuming rails1 is your rails directory)

Copy all  my views to your example views directory:

>cp ~paulp/cs316programs/rails/*.erb  app/views/example


From a browser start the example:

You should see the example screen. You can see it running on my port:


If “customer data” is selected, you can enter any of the above customer numbers and see a display of the customer data for that customer. If “sales rep” is selected, enter a sales rep number (03, 06, 12) and the customers for that sales rep are displayed.


While RoR is running the session where you started it is connected to RoR and shows RoR messages as applications are executed.


To restart Ruby on Rails in a new Multilab session, always run the three commands:

% bash
$ source /usr/local/rvm/scripts/rvm

Always run this command from your rails directory:

~/rails1$ rails server --port=xxxx --binding=

Debugging in the same session, after you have canceled Ruby on Rails (with ctl-c), you only have to run the third command to start it again.

The old RoR installation can be canceled using ctl-c. However, if you get a "port in use" error trying to restart it, there was an error canceling it. Do the netstat command above. You will see it still running. For example:

tcp 0 0 *:1234 *:* LISTEN paulp 18507298 23419/ruby

The RoR application is listening on port 1234. If this happens, you can kill the application using the Linux command kill:

kill -9 23419

Note that you kill the PID (process identifier) of the application, 23419 in the above example.

Explanation of how the ROR example works

When you enter in a browser:

The server looks for a program listening on port 1234 (the port where ROR was started). The entries in the routes.rb file direct the get and post requests for example:

get '/example/', to: 'example#index'

post '/example/result', to: 'example#result'

ROR looks for a file named index.html.erb in the views/example directory.

For program 5 add statements in the routes.rb file:

get '/example/', to: 'program5#index'

post '/example/result', to: 'program5#result'

In index.html.erb, when the submit button is pressed the form line (line 17) causes the result method in the example controller (action=”example/result”) in the controllers directory (example_controller.rb) to be executed. The result method gets the data entered in the text box and the request (lines 20-21), then checks for nondigits in the data (line 23). If nondigits are present, the invald.html.erb file in the views/example directory is executed (line 25).

For program 5 add a controller to the app/controllers directory: program5_controller.rb

The case statement (based on the request) selects which screen to display (lines 27-40). The screens (.erb file types) are in the views/example directory.

For program 5 create a program5 directory in the views directory. Put the screen files for program 5 in it.

Line 30 is an example of checking a table for the existence of a specific key (what the user provided in the textbox).

In the XXXX. html.erb files, lines are HTML items unless enclosed in <%     %>. Lines within these tags are Ruby code.

Note that variables are shared (can be read/modified) between the controller and the views.