Ruby on Rails on Oracle: A Simple Tutorial
by Richard Monson-Haefel (with mods for Rails 2.3 and ActiveRecord Oracle enhanced adapter by Jesse Hu)
Updated April 2009
Rails is an easy framework to work with, but like any technology it takes time to master.
You may have already heard about Ruby on Rails, the new application framework that seems to be taking the Web development community, in particular JEE and PHP programmers, by storm.
Rails is a capable Web application platform and has gained significant traction among JEE and PHP programmers. That attraction makes a lot of sense when you consider 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 fact explains its attraction to JEE 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-composite, primary key. Composite primary keys are supported via a Rails plugin! In addition, Rails supports multiple databases and can coordinate transactions among them; Rails does not support two-phase commit.
This article is not intended to be a booster piece for Rails nor is it an exposé. 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 JEE, 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
In 2005 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 create a schema for this sample Rails application. 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. Oracle Database 11g is used in this tutorial.)
Using SQL*Plus, create a user that you can use for this application.
SQL> GRANT CONNECT, RESOURCE TO ruby IDENTIFIED BY ruby; SQL> ALTER USER ruby DEFAULT TABLESPACE users TEMPORARY TABLESPACE temp; SQL> EXIT
If you use a remote Oracle database, you need to install the Oracle Database Instant Client which allows you to run your applications without installing the standard Oracle client or having an ORACLE_HOME. To install it, do the following:
- Go to the download page for Oracle Instant Client for Windows.
- Download instantclient-basic-win32-188.8.131.52.0.zip .
- Unzip the file under a directory.
- Add path to the directory in the environment variable PATH.
Step 2: Install Ruby, RubyGems, Rails, and the Ruby/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 2.3.2(the latest version of Rails), and the Ruby/Rails Oracle database library. To download and install Ruby with the Gems package installer, do the following:
- Go to http://rubyinstaller.rubyforge.org/.
- Download the "One-Click Ruby Installer for Windows 1.8.6-26 Final Release".
- 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, first you need to update RubyGems because Rails 2.3.2 requires RubyGems 1.3.1 (or higher):
C:\> gem update --system
Then install Rails:
C:\> gem install rails -v 2.3.2
Now that you have Ruby, RubyGems, and Rails installed, you can install a specialized code library that will allow your Ruby/Rails applications to talk to your Oracle database server. To install Ruby Oracle library and ActiveRecord Oracle Adapter, execute the following commands:
C:\> gem install ruby-oci8 -v 1.0.4 C:\> gem install activerecord-oracle-adapter --source http://gems.rubyonrails.org
Another choice for the ActiveRecord Oracle Adapter is the ActiveRecord Oracle enhanced adapter busily maintained by Oracle ACE Raimonds Simanovskis. This adapter contains useful additional features for working with new and legacy Oracle databases which are extracted from real projects' patches for the original ActiveRecord Oracle adapter ( activerecord-oracle-adapter), and supports three major Ruby interpreters (MRI 1.8.6, JRuby 1.1.6 and Ruby/YARV 1.9.1). To install ActiveRecord Oracle enhanced adapter, execute the following command:
C:\> gem install activerecord-oracle_enhanced-adapter
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 -d oracle
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: oracle database: comics_catalog_development username: comics_catalog 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: oracle database: comics_catalog_test username: comics_catalog password: production: adapter: oracle database: comics_catalog_production username: comics_catalog 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.) When using an Oracle Database on a remote machine, the file will look like this:
development: adapter: oracle database: <IP>/<SID> username: ruby password: ruby
If you use ActiveRecord Oracle enhanced adapter, specify 'oracle_enhanced' instead of 'oracle' as the adapter.
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, which will build the entire application in a single command.
C:\comics_catalog> ruby script/generate scaffold comic title:string issue:integer publisher:string
Here "title:string" represents a table column with the type "string" in Rails which is corresponding to the type "varchar2" in Oracle.
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.
You haven't created any database tables yet. Rails can help you in a simple way, execute the following command and the table "comics" will be created:
C:\comics_catalog> rake db:migrate
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 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.
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 the sample data.
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.
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.
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).
Richard Monson-Haefel ( http://www.monson-haefel.com/) is a senior experience architect at CSG and the author of Enterprise JavaBeans (O'Reilly, 2004), J2EE Web Services (Addison-Wesley, 2003), and Java Message Service (O'Reilly, 2000). He was a founder of the Apache J2EE Application Server Project (Geronimo) as well as the OpenEJB project.
Jesse Hu ( email@example.com) is a developer on the technical staff at Oracle Asia Research & Development Center.