Original URL: http://www.theregister.co.uk/2006/07/03/ruby_rails_part1/

Ruby on Rails

Simpler than J2EE

By Deepak Vohra

Posted in Developer, 3rd July 2006 06:32 GMT

Tutorial Ruby is an object oriented scripting language. Rails is a Model-View-Controller (MVC) framework based on Ruby and used for developing web applications. An advantage of Ruby on Rails over J2EE is that it requires less code and doesn’t require any configuration files, except for a database configuration file. A Ruby on Rails web application may be developed simply with a web server and a database; and the Rails framework includes a built-in web server, WEBrick (another web server such as Apache may also be used). The Rails framework is configured for the MySQL database by default but Rails also supports PostgreSQL, SQL Server, Oracle and DB2 databases.

Overview of Ruby

Ruby is an interpreted scripting language for object-oriented programming: “interpreted” implies that a Ruby application is run without first compiling the application. Variables in Ruby do not have a type (a Ruby variable may contain data of any type). Variables in Ruby may be used without any variable declarations. Ruby, being an object oriented language, has features such as classes, inheritance and methods.

Overview of Rails

Rails is a web application and database persistence framework for developing web applications according to the MVC pattern. Models are used to model objects in a Rails application and are typically based on ActiveRecord. An ActiveRecord model class extends the ActiveRecord::Base class. Models provide object-relational mapping (ORM) between business objects and a database. Views are the user interfaces and are represented by RHTML or RXML templates, RHTML being Ruby embedded HTML, and RXML Ruby-generated XML. The controller is a class that extends the ActionController::Base class and consists of actions (methods). For each method in a controller class, you either define a view template with a matching name, redirect to a view template or a controller action or render text in the template that invoked the controller action with render :text method. A view template contains links to actions (methods) defined in the controller. A controller integrates the model with the view. The model models data objects, the controller defines business logic to process the data, and the view presents the data.

The model and controller scripts may be generated with Ruby on Rails commands, some of which are discussed in the table below:

Command (Variables are in italics) Description
rails applicationname Creates a Rails application of specified application name.
ruby script/server Starts WEBrick web server, which may be accessed at url http://localhost:3000
ruby script/generate model modelname Generates a model class, which extends ActiveRecord::Base class.
ruby script/generate controller controllername Generates a controller class, which extends the ApplicationController class.
ruby script/generate scaffold modelname controllername Generates a model class, which includes the scaffolding, and a controller class. controllername is optional in the scaffold generator command.
ruby script/generate migration migrationname Generates a ActiveRecord migration script.

Installing Ruby on Rails

In this section we shall install the Ruby on Rails framework, and RubyGems. RubyGems is the standard Ruby package manager. Download the Ruby Windows Installer application and double-click on the ruby184-19.exe application. Ruby Setup Wizard gets started in which click on Next and accept the license agreement. Select the default components to install, which include the RubyGems package manager. Specify a directory to install Ruby, c:/ruby being the default, and click on Install. Ruby and RubyGems gets installed. Next, install Rails. From the c:/ruby directory, the directory in which Ruby is installed, run the following command to install Rails and dependencies including activerecord and actionpack - Activerecord implements the model components of a Rails MVC application and actionpack implements the view and controller components:

c:/ruby>gem install rails --include-dependencies

Now install Oracle database 10g including sample schemas and create a database instance, ORCL for example. Next, install Ruby driver for Oracle database, which is required to connect to Oracle database from a Ruby on Rails application. Download this file (ruby-oci8-0.1.15-mswin32.rb) to c:/ruby directory and from the c:/ruby directory run the Ruby application for Oracle database drive:

 c:/ruby>ruby ruby-oci8-0.1.15-mswin32.rb

This installs the Ruby driver for the Oracle database. Next, we shall create a Rails application, rubyrails, using the following command:

 c:/ruby>rails rubyrails

This generates a Rails application directory structure. The root directory of the Rails application is rubyrails. The app sub-directory consists of sub-directories models, views and controllers for model scripts, view templates and controller scripts. The config directory consists of a database.yml configuration file, used to define a database configuration (as mentioned, by default this is configured for MySQL database). The db directory consists of a sub-directory migrate that consists of migration scripts.

Creating a Database Table

In this article we shall develop a Rails application with CRUD (Create, Read, Update, Delete) functionality. The example application requires a database table, which we shall create in this section. A database table may be created using ActiveRecord migrations. A migration is a class that extends the ActiveRecord::Migration class and is run with the rake command. First, we need to configure the database.yml configuration file in the config directory of the example Rails application, rubyrails, to use the Oracle database. A migration runs in the development environment by default, but may also be run in production environment or test environment - modify the development environment settings in database.yml file for the Oracle database to as shown in following listing.

 development:
 adapter: oci
  database: ORCL
  username: OE
  password: password
  host:

The host value should be kept empty and the space between the ‘:’ and the configuration values is required: for example, specify adapter: oci instead of adapter:oci.

A migration script may be created with the following command:

 c:/ruby>ruby script/generate migration migrationname

Variable migrationname specifies the migration name. A migration may also be created by creating a model script, which also creates a migration script. As we shall be creating a MVC application, the migration script will be created by generating a model script. To create a model script, catalog.rb, Cd(change directory) to the rails application root directory, rubyrails, and run the following command:

 C:>ruby>rubyrails>ruby script/generate model catalog

Model class script catalog.rb gets generated in the models sub directory of the app sub directory. A migration script, 001_create_catalogs.rb , which consists of CreateCatalogs class gets generated in the migrate sub directory of the db sub directory. The migration class, CreateCatalogs, extends the ActiveRecord::Migration class. The default migration script is listed below:

 class CreateCatalogs < ActiveRecord::Migration
  def self.up
    create_table :catalogs do |t|     
     # t.column :name, :string   
    end
  end
  def self.down
   drop_table :catalogs
  end
end

A default migration consists of actions self.up and self.down. Method self.up consists of Ruby code to implement the migration and self.down consists of Ruby code to rollback the migration. In the CreateCatalogs class, self.up consists of transformation create_table, used to create a catalogs table. ActiveRecord uses pluralisation to map a model class to a database table. The model class is singular and capitalized and the database table is plural and lowercase (for example, if the model class is Catalog, the table name is catalogs). The self.down method in CreateCatalogs class consists of a drop_table transformation to drop database table catalogs. A migration class may define migration transformations, as discussed in following table:

Transformation Description
create_table(name, options) Used to create a table.
drop_table(name) Used to drop a table.
rename_table(old_name, new_name) Used to rename a table.
add_column(table_name, column_name, type, options) Used to add a column to a table.
rename_column(table_name, column_name, new_column_name) Used to rename a table column.
change_column(table_name, column_name, type, options) Used to change a column to a different type.
remove_column(table_name, column_name) Used to remove a column.
add_index(table_name, column_name, index_type) Adds an index.
remove_index(table_name, column_name) Removes an index.

Next, we’ll modify the migration class, CreateCatalogs, to create a table, add columns to the table and initialize the table with data. To the catalogs table add columns journal, publisher, edition, title, author of type string and size 255. The example migration script uses the block form of create_table.

create_table :catalogs do |t|
   t.column :journal, :string, :limit => 255
   t.column :publisher, :string, :limit => 255
   t.column :edition, :string, :limit => 255
    t.column :title, :string, :limit => 255
   t.column :author, :string, :limit => 255
   end

Column types that may be added are integer, float, datetime, timestamp, time, text, string, binary and boolean. Add data to the catalogs table with ActiveRecord::Base class method create. An example row is added as shown below:

 Catalog.create :journal => "Oracle Magazine",
 :publisher => "Oracle Publishing",
 :edition => "Nov-Dec 2004",
 :title=> "From ADF UIX to JSF",
 :author=>"Jonas Jacobi"

The complete migration script to create example database table catalogs is listed in following listing:

class CreateCatalogs < ActiveRecord::Migration
  def self.up
  create_table :catalogs do |t|
   t.column :journal, :string, :limit => 255
   t.column :publisher, :string, :limit => 255
   t.column :edition, :string, :limit => 255
    t.column :title, :string, :limit => 255
   t.column :author, :string, :limit => 255
   end
   
Catalog.create :journal => "Oracle Magazine",
 :publisher => "Oracle Publishing",
 :edition => "Nov-Dec 2004",
 :title=> "From ADF UIX to JSF",
 :author=>"Jonas Jacobi"

Catalog.create :journal => "Oracle Magazine",
 :publisher => "Oracle Publishing",
 :edition => "Nov-Dec 2004",
 :title=> "Database Resource Manager",
 :author=>"Kimberly Floss"


  end

  def self.down
  drop_table :catalogs
  end
end

Next, run the migration with rake; Rake is similar to Java’s ant. Rails has a target called migrate to run migrations. Change directory (Cd) to the rubyrails directory and run the following command:

c:/ruby/rubyrails>rake migrate

This generates an Oracle database table called catalogs along with a sequence catalogs_seq. This will be used in the next Ruby on Rails tutorial, where we’ll create a MVC CRUD application &reg:.