Wednesday, May 28, 2008

Ruby on Rails on Oracle: A Simple Tutorial

Source: Oracle.com

Ruby on Rails on Oracle: A Simple Tutorial

by Richard Monson-Haefel

Rails is an easy framework to work with, but like any technology it takes time to master.

Published April 2006

Comments about this article? Visit the Ruby/RoR Discussion Forum

You may have already heard about Ruby on Rails, the new application framework that seems to be taking the Web development community, in particular J2EE and PHP programmers, by storm.

Rails is a capable Web application platform and has, in less than two years, gained significant traction among J2EE and PHP programmers. The attraction of both J2EE and PHP programmers makes a lot of sense when you look at the strengths of Rails. For one thing, it uses a strict model-view-controller architecture that any self-respecting design-patterns wonk would admire—this explains its attraction to J2EE developers. Second, it’s easy to build basic systems with Rails—which is attractive to PHP developers.

However, Rails has some pretty significant limitations from a database perspective. Rails makes a lot of assumptions about your database layout and application needs. For example, Rails assumes that all tables use a single, non-compound, primary key. Compound primary keys are not supported! In addition, Rails does not support two-phase commit; it supports multiple databases, but cannot coordinate transactions among them.

This article is not intended to be a booster piece for Rails nor is it an expose. It’s simply an introduction to the technology. It contains both praise and criticism. At times the criticism might appear a bit heavy handed (especially to Rails enthusiasts), but don’t be fooled. Using any Web application framework is going to be tricky, whether it’s J2EE, ASP.NET, or PHP. In the long run, you can be a lot more productive with Rails than you can be with many other Web application development platforms, but it takes time to learn the ropes.

What is Ruby? What is Rails?

Ruby is a dynamic programming language similar in many respects to Perl, Python, and Smalltalk, but it is its own animal. Java and PHP programmers seem to pick up the language pretty easily and they have been Ruby’s biggest supporters. But others have been attracted to the language, too; including Don Box, who is well known as one of the wonkiest-wonks of the Microsoft world.

Ruby is not new; it was created in 1993, making it older than Java or PHP, both of which were first introduced to the public in 1995. So while Ruby is a mature language, it’s been less popular than some other languages. As a result, the ecosystem that surrounds the Ruby programming language is not as rich as those that have grown up around Java, PHP, or Perl. Consequently, you will find fewer frameworks, libraries, books, Web sites, blogs, and other resources dedicated to the language.

The marketing impotence of the Ruby community changed recently, when David Heinemeier Hanson introduced the Rails framework, arguably the most popular application of Ruby in its history. Rails extends the Ruby programming language into a domain specific language especially well suited for web development. It also leverages ActiveRecord, another language extension that adapts Ruby to object-relational persistence. Other than Rails’ lack of support for compound primary keys and two-phase commit, its biggest obstacle to adoption has been that you need to learn a new programming language to use it. This is not something that most people can simply ignore with a lot of hand-waving; learning a new language can be a fun but daunting task.

If, however, you were interested in expanding your resume, I can think of no other language I would recommend higher than Ruby. Ruby represents the culmination of 10 years of development without the tampering of commercial interests. As a result, Ruby is a delight to work with and, in many cases, is an order of magnitude more productive than Java, C, or Microsoft .NET languages. (The exception may be IronPython, a port of the Python language to the Microsoft .NET environment. Python, like Ruby, is a dynamic and productive programming language.)

What is Rails For?

Rails is designed from the ground up to create dynamic Web sites that use a relational database backend. It adds key words to the Ruby programming language that make Web applications easier to configure. In addition, it’s designed to automatically generate a complete, if somewhat crude, Web application from an existing database schema. The latter is both Ruby’s greatest strength and its Achilles’ heel. Rails makes assumptions about database schema naming conventions that, if followed, make generating a basic Web site a matter of executing single command. But to do this may require additional configurations or in some cases may not be possible at all. You’re also likely to find that just about every database convention that Rails expects can be overridden, but the more overriding that is needed, the less productive the platform becomes. This is why Rails is great when developing “green-field” applications with new databases. Unfortunately, it’s not a great solution when dealing with legacy systems.

The best way to appreciate Rails in green-field application development is via an example. If you already have an Oracle database installed on which you can create new databases and tables, it should take less than 15 minutes to create a complete Web application. In this case, we’ll use Ruby of Rails to build a product catalog.

Example: A Simple Product Catalog

Last year I started investing in high-grade (HG) comic books, specifically old issues from as far back as 1946. I created a simple Ruby on Rails database application that allows me to insert, remove, modify and delete new comics as I buy and sell them. It’s only intended for my use, so I kept it pretty simple. The application that will be developed in this article is a trimmed down version of the Ruby on Rails application I use at home.

Although Rails and Oracle Database can be used on a variety of platforms, this article focuses on Windows XP, arguably one of the most frequently used operating systems by Oracle application developers. This example is pretty simple; it’s essentially the database equivalent of a “Hello World” programming language example. It’s designed to give you a small taste of Ruby, but it doesn’t represent the full capabilities of Rails, any more than a “Hello World” example demonstrates the full capabilities of any programming language.

If you experience problems running this example, it’s likely to be for one of three reasons: Either you downloaded the wrong code, your database is not set up to allow you to connect to it, or your Windows XP operating system is giving you problems. In developing this example, I had a number of problems related to versioning and database configuration—all of which were a result of ignorance. I leaned heavily on a friend of mine, Michael Carland, to get everything working and to make this example as simple as possible.

The fact of the matter is, getting Ruby on Rails and Oracle to work together is not trivial. In fact, it can be a bit frustrating at times. Follow the directions in this article exactly and you shouldn’t have problems. However, once you step outside the boundaries of this example, expect to have some issues. Rails can be very productive, but it’s a command-line development environment and doesn’t come with all of the “automagic” typically associated with advanced integrated development environments. If you are not a “do-it-yourself” technical person, than I wouldn’t recommend Rails to you at this time.

Step 1: Set up the Oracle database

You wouldn’t be reading this article if you were not interested in using Rails in combination with Oracle, so you’ll need to have an installed instance of the Oracle database and you’ll need to add a single table to the database. It’s important that you follow the exact naming conventions used in this article, otherwise a lot of the automatic code generation provided by Rails simply won’t work (without some tweaking). The table you need to create is described as follows:

CREATE TABLE comics ( id NUMBER(10) NOT NULL, title VARCHAR2(60), issue NUMBER(4), publisher VARCHAR2(60), PRIMARY KEY (id) ); CREATE SEQUENCE comics_seq;

There is a SQL Script file here which you can use to create the table and add some product data. I suggest that you use it so that your application is consistent with the one being developed here. The easiest way to do that is to use SQL*Plus as follows. (The assumption is that you already have an Oracle database installed and know how to use it.)

Using SQL*Plus, create a user with DBA privileges that you can use for this application.

SQL> GRANT dba TO ruby IDENTIFIED BY ruby; SQL> ALTER USER ruby DEFAULT TABLESPACE users TEMPORARY TABLESPACE temp; SQL> EXIT

Using the SQL file, create the application table, COMICS, and insert some example data.

C:\> sqlplus ruby/ruby@rails @comics.sql

As you may have noticed, the COMICS table created for this example is plural, which may appear problematic since a common approach is to give tables singular names (e.g. COMIC). However, Rails takes the approach that tables should be named in the plural. This default can be overridden using a Rails configuration but using plural names is easier.

Step 2: Install Ruby, RubyGems, Rails, and the Rails Oracle library

There are two pieces of software you’ll need in order to use Rails on Windows XP: the Ruby programming language with RubyGems installation package, Rails 1.0 (1.1 was recently released; this articles addresses 1.0 only), and the Rails Oracle database library. To download and install Ruby with the Gems package installer, do the following.

  1. Go to http://rubyinstaller.rubyforge.org/.
  2. Download the “One-Click Ruby Installer”.
  3. Follow the installation instructions.

Once the Ruby programming platform is installed you can use RubyGems, a Ruby application that allows you to install Ruby frameworks very easily. To install the Rails application development framework, all you need to do is open a command-line prompt and type in a single command.

C:\> gem install rails -v 1.0.0 --remote

Now that you have Ruby, RubyGems, and Rails installed you can install a specialized code library that will allow your Rails applications to talk to your Oracle database server. To download and install Oracle Rails library, go to http://rubyforge.org/projects/ruby-oci8, download ruby-oci8-0.1.13-mswin.r to your C drive, and then using your command window, execute the following command.

C:\> ruby ruby-oci8-0.1.13-mswin.rb

Assuming that everything went smoothly, you have now installed Ruby, Rails, and the Rails-Oracle connection library. You are now ready to create your first Ruby on Rails Web application.

Step 3: Create the Web Application

In order to create your new Rails application, you will need to create a new Rails project as follows.

Create a new project using the rails command line application (this will automatically create a new directory).

C:\> rails comics_catalog

Change directories so you are in the new project directory created in the previous step.

C:\> cd comics_catalog C:\comics_catalog>

Now that you have a new Rails project directory, you’ll need to configure your project so that the Rails applications will use the Rails-Oracle connection library.

Within your project directory, there is a directory called config and in it is a file named database.yml. You need to edit database.yml using your favorite text editor. Initially, the file will look like this:

development:
adapter: mysql
database: rails_development
host: localhost
username: root
password:

# Warning: The database defined as 'test' will be erased and
# re-generated from your development database when you run 'rake'.
# Do not set this db to the same as development or production.
test:
adapter: mysql
database: rails_test
host: localhost
username: root
password:

production:
adapter: mysql
database: rails_production
host: localhost
username: root
password:

Different databases require different connection properties. Rails is set up to work with MySQL by default, but you want to re-configure this project to use Oracle. Change the development properties as described on this Oracle on Rails wiki page. (You could change the test and production properties also, but the scope of this article doesn’t include testing or production releases.)

There are a number of approaches to creating a Web application in Rails, but the simplest by far is to use scaffold, a command line feature in Rails 1.0.0, which will build the entire application in a single command.

C:\comics_catalog> ruby script/generate scaffold Comic

Other than a cascade of output in the command window, what just happened? Well, the Rails code generator created model, view, and controller Ruby code to access the COMICS table. In this case you created the application using the Rails scaffold, which does all the work for you. If you make any changes to the database tables, you’ll need to run the scaffold command again. Otherwise, your application may not work.

Now that the web application has been generated, you can start the Ruby Web server, WEBRick.

C:\comics_catalog> ruby script/server

You can change the Ruby code for your application or the COMICS table at anytime without having to restart the web server. However, if you change the database configuration file (i.e. database.yml) you will need to restart the server.

Now you can access your Rails Comic Catalog application on your own development machine, using your favorite Web browser. Just access the following URL.

http://localhost:3000/comics/list

Your browser should show a list of comics in your Catalog like the one in Figure 1.


Figure 1: Product Catalog List

When you use the scaffold to create a Rails Web application, it will automatically create three Web components that allow you to see a list of all records in the target database table and to insert, modify, and delete records in that table. Figure 1 shows a list of all of the sample data that was inserted into your database table when you executed the SQL script at the start of this tutorial.

In addition to the Listing view, there is also a details view. Just click on any of the “Show” links to see a Web paged dedicated to displaying the data in that particular record. Figure 2 is an example of this details page.


Figure 2: The Details Page

You can also edit any record in the database table. Click on the “Back” link, or use your browser back button to get back to the Listing page, then click on the “Edit” link of any record. Figure 3 shows an example of the Editing view of one of the records in the COMICS database table.


Figure 3: The Editing View

You can also add new records to the COMICS table by going back to the Listing view and clicking on the “New Comic” link. This will present you with an insertion view similar to the one in figure 3, except the fields will all be blank.

Mastering Rails

While the Product Catalog example showed how easy it is to create a very simple application using Rails, it’s not all that useful except for tracking inventory. You can create much more complicated Web applications with Rails, but that will require that you jump into the code a bit, which would require some study. Rails is an easy framework to work with, but like any technology it takes time to master. At this point, I can only recommend Rails to technically-savvy individuals and development teams who are embarking on “green-field” application development. If you don’t fall into this rough category, I wouldn’t recommend using Rails until the tooling has matured.

In order to really master Rails, you should read a book, a number of which will be available later this year, but one that is very good and is available now is Agile Web Programming with Ruby on Rails by David Heninmier Hanson and Dave Thomas (Published by Pragmatic Bookshelf, 2005). Hanson is, of course, the guy who created Rails and Thomas is one of the authors of Programming Ruby: The Pragmatic Programmers' Guide (Pragmatic Bookshelf; 2nd edition, 2004).


No comments: